尝试在MySQL查询中排除不需要的GROUP BY类别

时间:2013-11-25 04:27:28

标签: mysql

我能够正常运行以下查询,除了结果返回“Archived”和“Rejected”(状态列中的另外两个状态)的空行,我希望从结果中排除< / p>

SELECT status,
sum(case when status = 'New' then 1 else 0 end),
sum(case when status = 'Active' then 1 else 0 end),
sum(case when status = 'Closed' then 1 else 0 end)
FROM Contact
GROUP BY status

现在查询返回:

0             1   2   3
Archived      0   0   0
Rejected      0   0   0
New           5   0   0
Active        0   4   0
Closed        0   0   7

我想让它回来:

0             1   2   3
New           5   0   0
Active        0   4   0
Closed        0   0   7

任何帮助指明我正确方向的人都将不胜感激。

3 个答案:

答案 0 :(得分:4)

在GROUP BY子句之后添加HAVING status NOT IN('Archieved', 'Rejected')

答案 1 :(得分:3)

尝试从您的选择中逐字排除;

SELECT status,
sum(case when status = 'New' then 1 else 0 end),
sum(case when status = 'Active' then 1 else 0 end),
sum(case when status = 'Closed' then 1 else 0 end)
FROM Contact
WHERE Status <> 'Archived'
AND   Status <> 'Rejected'
GROUP BY status

答案 2 :(得分:1)

您只需要添加having子句

SELECT status,
sum(case when status = 'New' then 1 else 0 end),
sum(case when status = 'Active' then 1 else 0 end),
sum(case when status = 'Closed' then 1 else 0 end)
FROM Contact
GROUP BY status
Having status NOT IN('Archieved', 'Rejected');


为了更好地理解它,只需使用Having

即可