sql - 将合并、计数、案例和子句组合在一起

标签 sql coalesce

我是新手,所以请多多包涵。

我正在编写一个查询,我需要计算具有两个特定值的行数,

我已使用以下方法获取一个字段中不同值的结果,但仅当另一个字段设置为特定值时我才需要知道结果。我从本网站上一个问题中提取了以下内容:

COALESCE(count(case when CW.MAINJOBROLE = 2 THEN 1 end),0) as ALLJOBROLES_2,
coalesce(count(case when CW.MAINJOBROLE = 3 then 1 end), 0) as ALLJOBROLES_3,
coalesce(count(case when CW.MAINJOBROLE = 4 then 1 end), 0) as ALLJOBROLES_4,
coalesce(count(case when CW.MAINJOBROLE = 7 then 1 end), 0) as ALLJOBROLES_7,
coalesce(count(case when CW.MAINJOBROLE = 8 then 1 end), 0) as ALLJOBROLES_8,
coalesce(count(case when CW.MAINJOBROLE = 23 then 1 end), 0) as ALLJOBROLES_23,
coalesce(count(case when CW.MAINJOBROLE = 24 then 1 end), 0) as ALLJOBROLES_24,
coalesce(count(case when CW.MAINJOBROLE = 25 then 1 end), 0) as ALLJOBROLES_25'

作为更大查询的一部分,我只想在 CW.EMPLSTATUS = 1

时执行上述操作

最佳答案

您可以将条件添加到 where 子句中:

COALESCE(count(case when CW.MAINJOBROLE = 2 and CW.EMPLSTATUS = 1 THEN 1 end),0) as ALLJOBROLES_2,

顺便说一下,COALESCE() 应该是不必要的。如果没有匹配项,COUNT() 将返回 0

关于sql - 将合并、计数、案例和子句组合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25932692/

相关文章:

php - MySql COALESCE 不工作

mysql - 使用合并在数据库中查找重复项

sql - 在没有数据时也提取日期值

MySQL 选择给定日期之前的最新日期来计算 SUM(#)

hibernate - JPA 中 Coalesce 或 Case 语句的使用

mysql - SQL 中的 Long Boolean Where

mysql - 用表的 id 替换字符串值的最后一个字符

postgresql - 修改 COALESCE 函数以考虑结果的两个相邻值

sql - 如何自动化此日期代码,这样我就不必每年都更改它?

mysql - SQL 查询返回多个表中通过特定条件的元素