如何在SQL中对GROUP BY Query的结果进行分组?

时间:2015-02-18 14:10:22

标签: sql group-by

我的SQL查询是:

SELECT Comments, COUNT(Comments) [Total] 
FROM Completed_Scrubs 
GROUP BY Comments

结果是:

Comments    Total
------------------
Cus           202
WEA             1
Process        13
Rework         30
Non           893
Prob            1
App            10

我想将不同的行添加为:

(Cus + WEA) = Uncontrolled
(Process + Rework) = Controlled
(Non+Prob+App) = Business

所以结果应该是:

Comments        Total
----------------------
Uncontrolled     203
Controlled        43
Business         904

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

您可以在此处使用CASE语句来定义您的输出,并在GROUP BY

SELECT 
(CASE WHEN Comments in ('Cus','WEA') THEN 'Uncontrolled'
      WHEN Comments in ('Process','Rework') THEN 'Controlled'
      WHEN Comments in ('Non','Prob','App') THEN 'Business'
 END) as Comments,
COUNT(Comments) [Total] 
FROM Completed_Scrubs 
GROUP BY (CASE WHEN Comments in ('Cus','WEA') THEN 'Uncontrolled'
              WHEN Comments in ('Process','Rework') THEN 'Controlled'
              WHEN Comments in ('Non','Prob','App') THEN 'Business'
          END)

答案 1 :(得分:1)

非常简单的解决方案,计算每种类型并将结果结合在一起:

select 'Uncontrolled', count(*)
from Completed_Scrubs where comments in ('Cus', 'WEA')
union all
select 'Controlled', count(*)
from Completed_Scrubs where comments in ('Process', 'Rework')
union all
select 'Business', count(*)
from Completed_Scrubs where comments in ('Non', 'Prob', 'App')

或者更高级一点:

select status, count(*) from
(select case when comments in ('Cus', 'WEA') then 'Uncontrolled' 
             when comments in ('Process', 'Rework') then 'Controlled' 
             when comments in ('Non', 'Prob', 'App') then 'Business' 
             else 'Invalid' end as status
 from Completed_Scrubs)
group by status