[英]mysql multiple counts in a single query
SELECT SUM( CASE WHEN is_half = 1 THEN 1 ELSE 0 END ) halfCount, SUM( CASE
WHEN is_half = 0 THEN 1 ELSE 0 END ) totalCount FROM employee_leave WHERE
YEAR(leave_date_from) = YEAR(CURRENT_DATE()) AND employee_id="EMP12" AND
leave_status=1
With this query I am getting results as(If there are no values): 通过此查询,我得到的结果为(如果没有值):
halfCount | totalCount
NULL | NULL
How can I get 0 instead of NULL? 如何获得0而不是NULL?
Desired output: 所需的输出:
halfCount | totalCount
0 | 0
Assuming your query is correct, you can use COALESCE to change null into 0 (or any other number) 假设查询正确,则可以使用COALESCE将null更改为0 (或任何其他数字)
SELECT COALESCE(SUM( CASE WHEN is_half = 1 THEN 1 ELSE 0 END ), 0) as 'halfCount',
COALESCE(SUM( CASE WHEN is_half = 0 THEN 1 ELSE 0 END ), 0) as 'totalCount'
FROM employee_leave
WHERE YEAR(leave_date_from) = YEAR(CURRENT_DATE()
AND employee_id="EMP12"
AND leave_status=1
I'm not really sure if this is error-free, as I can't test it in my machine, but that is how to use COALESCE
我不确定这是否没有错误,因为我无法在我的机器上对其进行测试,但这就是如何使用
COALESCE
try this 尝试这个
SELECT IFNULL(SUM( CASE WHEN is_half = 1 THEN 1 ELSE 0 END ),0) halfCount, IFNULL(SUM( CASE
WHEN is_half = 0 THEN 1 ELSE 0 END ),0) totalCount FROM employee_leave WHERE
YEAR(leave_date_from) = YEAR(CURRENT_DATE()) AND employee_id="EMP12" AND
leave_status=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.