当其中一个组的计数为零时,将结果包括在GROUP BY中

时间:2013-12-09 19:21:16

标签: mysql

我成功运行了以下查询,但需要在返回的结果中表示所有状态,即使某种状态为零:

SELECT status,
sum(case when status = 'New' then 1 else 0 end),
sum(case when status = '1 Attempt' then 1 else 0 end),
sum(case when status = '2 Attempts' then 1 else 0 end),
sum(case when status = '3 Attempts' then 1 else 0 end),
sum(case when status = 'Connected' then 1 else 0 end),
sum(case when status = 'Follow Up' then 1 else 0 end),
sum(case when status = 'Referred' then 1 else 0 end)
FROM Contact
GROUP BY status
HAVING status NOT IN('Invalid', 'Archived')
ORDER BY FIELD (status, 'New', '1 Attempt', '2 Attempts', '3 Attempts', 'Connected',    'Follow Up', 'Referred')

目前,如果有1个“新”状态和1个“已连接”状态,我会得到这些结果:

0          1 2 3 4 5 6 7
New        1 0 0 0 0 0 0
Connected  0 0 0 0 1 0 0

我想要的是上面的情况是:

0          1 2 3 4 5 6 7
New        1 0 0 0 0 0 0
1 Attempt  0 0 0 0 0 0 0
2 Attempts 0 0 0 0 0 0 0
3 Attempts 0 0 0 0 0 0 0
Connected  0 0 0 0 1 0 0
etc...

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:1)

尝试:

SELECT p.status as `0`,
sum(case when c.status = 'New' then 1 else 0 end) as `1`,
sum(case when c.status = '1 Attempt' then 1 else 0 end) `2`,
sum(case when c.status = '2 Attempts' then 1 else 0 end) `3`,
sum(case when c.status = '3 Attempts' then 1 else 0 end) `4`,
sum(case when c.status = 'Connected' then 1 else 0 end) `5`,
sum(case when c.status = 'Follow Up' then 1 else 0 end) `6`,
sum(case when c.status = 'Referred' then 1 else 0 end) `7`
FROM (
  SELECT 'New' Status
  Union SELECT '1 Attempt' Status
  Union SELECT '2 Attempts' Status
  Union SELECT '3 Attempts' Status
  Union SELECT 'Connected' Status
  Union SELECT 'Follow Up' Status
  Union SELECT 'Referred' Status
) p
LEFT JOIN Contact c ON p.status = c.status
GROUP BY p.status
HAVING status NOT IN('Invalid', 'Archived')
ORDER BY FIELD (p.status, 'New', '1 Attempt', '2 Attempts', '3 Attempts', 'Connected',    'Follow Up', 'Referred')

演示 - > http://www.sqlfiddle.com/#!2/9500f/1

答案 1 :(得分:0)

select status, sum(case when status ='New' then 1 else 0) as '1',0 as '2', 0 as '3', 0 as '4', ..., from Contact group by status 

Union

select status, 0 as '1' , sum(case when status ='1 Attempt' then 1 else 0) as '1',0 as '2', 0 as '3', 0 as '4', ..., from Contact group by status

Union


...

答案 2 :(得分:0)

这不完全是您需要的格式,但它会在一行中获取所需的数据,每个总和作为一列:

SELECT
SUM(CASE WHEN status = 'New' THEN 1 ELSE 0 END) AS count_new,
SUM(CASE WHEN status = '1 Attempt' THEN 1 ELSE 0 END) AS count_1_attempt,
SUM(CASE WHEN status = '2 Attempts' THEN 1 ELSE 0 END) AS count_2_attempts,
SUM(CASE WHEN status = '3 Attempts' THEN 1 ELSE 0 END) AS count_3_attempts,
SUM(CASE WHEN status = 'Connected' THEN 1 ELSE 0 END) AS count_connected,
SUM(CASE WHEN status = 'Follow Up' THEN 1 ELSE 0 END) AS count_follow_up,
SUM(CASE WHEN status = 'Referred' THEN 1 ELSE 0 END) AS count_referred
FROM Contact