mysql在单个查询中多次计数

时间:2017-10-24 09:48:20

标签: php mysql

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

使用此查询,我得到的结果为(如果没有值):

halfCount | totalCount
NULL      | NULL

如何获得0而不是NULL?

期望的输出:

halfCount | totalCount
0         | 0

2 个答案:

答案 0 :(得分:0)

假设您的查询正确,您可以使用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

我不确定这是否没有错误,因为我无法在我的机器上测试它,但这是如何使用COALESCE

答案 1 :(得分:0)

试试这个

npm run watch