当count = 0时,按分组计数

时间:2014-10-02 04:44:54

标签: mysql

我搜索了似乎相关的问题,但仍然无法解决我的问题。

SELECT c.name AS 'Computer', COUNT(h.hotfixid) AS '# Missing',
CASE
    WHEN COUNT(h.hotfixid) ='0' THEN 'Fully Patched'
    WHEN COUNT(h.hotfixid) BETWEEN 1 AND 4 THEN '1 - 4 Missing'
    WHEN COUNT(h.hotfixid) BETWEEN 5 AND 12 THEN '5 - 12 Missing'
    WHEN COUNT(h.hotfixid) >12 THEN 'Attention > 12 Missing' 
    END AS 'Status', 
c.os AS 'Operating System'
FROM hotfix h
LEFT JOIN computers c ON h.computerid=c.computerid
LEFT JOIN clients cl ON c.clientid=cl.clientid
WHERE h.Installed='0' AND h.Approved='1' AND c.clientid = '229'
GROUP BY c.name

问题是以上内容不会返回任何有0或没有记录的内容。 GROUP BY打破了它。

此查询返回我的预期结果,但是当我向其添加GROUP BY时,根本不会返回任何结果。

    SELECT 
CASE 
    WHEN COUNT(hotfixid) ='0' THEN 'Fully Patched'
    WHEN COUNT(hotfixid) BETWEEN 1 AND 4 THEN '1 - 4 Missing'
    WHEN COUNT(hotfixid) BETWEEN 5 AND 12 THEN '5 - 12 Missing'
    WHEN COUNT(hotfixid) >12 THEN 'Attention > 12 Missing'
    END AS 'Status'
FROM hotfix
WHERE computerid = '8176' AND hotfix.`approved` = '1' AND hotfix.`installed` = '0'

此查询返回0,所以我知道我得到0而不是'NULL'

SELECT computerid,
    COUNT(hotfixid) 
    FROM hotfix
    WHERE computerid = '8176' AND hotfix.`approved` = '1' AND hotfix.`installed` = '0'

编辑。

修补程序表信息:

enter image description here

我的预期输出是按机器列出,它们的修补状态,但完全修补状态不会显示:

MySQL Yog output

感谢您的帮助。

关心彼得。

1 个答案:

答案 0 :(得分:0)

computers离开加入hotfix更有意义。 c.os

中缺少group by.
SELECT c.name AS 'Computer', COUNT(h.hotfixid) AS '# Missing',
CASE
    WHEN COUNT(h.hotfixid) ='0' THEN 'Fully Patched'
    WHEN COUNT(h.hotfixid) BETWEEN 1 AND 4 THEN '1 - 4 Missing'
    WHEN COUNT(h.hotfixid) BETWEEN 5 AND 12 THEN '5 - 12 Missing'
    WHEN COUNT(h.hotfixid) >12 THEN 'Attention > 12 Missing' 
    END AS 'Status', 
c.os AS 'Operating System'
FROM computers c
LEFT OUTER JOIN hotfix h ON c.computerid=h.computerid AND h.Installed='0' AND h.Approved='1'
LEFT OUTER JOIN clients cl ON c.clientid=cl.clientid AND c.clientid = '229'
GROUP BY c.name, c.os