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

How to group the results of a GROUP BY Query in SQL?

我的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

任何帮助将不胜感激。

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

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

您可以在此处使用 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)