【1】需求
如何統計分類數量?
有些分類要合並統計, 例如: 統計亞洲和歐洲有多少國家,剩下的國家統計到"火星"
要求結果是這樣的:

【2】在sql group by 中使用 case when
【2.1】常規正向寫法
;WITH t1 AS ( SELECT 'Asia' Area,'china' country UNION all SELECT 'Asia' Area,'russia' country UNION all SELECT 'europe' Area,'england' country UNION all SELECT 'europe' Area,'germany' country UNION all SELECT 'Africa' area,'india' country ) SELECT CASE WHEN Area='Asia' THEN Area WHEN Area='europe' THEN Area ELSE 'spark' END AS AreaName,COUNT(1) country_num FROM t1 GROUP BY CASE WHEN Area='Asia' THEN Area WHEN Area='europe' THEN Area ELSE 'spark' end

這個寫法固然可以,但如果不只是亞洲、歐洲,而是有十幾個甚至幾十個相關項,難道要一個一個 when Area=value1 when Area=value2......Area=valueN 嗎?
顯示是不合適且冗余復雜的,這個時候就用到我們下面的【2.2】寫法
【2.2】反向批量寫法
;WITH t1 AS ( SELECT 'Asia' Area,'china' country UNION all SELECT 'Asia' Area,'russia' country UNION all SELECT 'europe' Area,'england' country UNION all SELECT 'europe' Area,'germany' country UNION all SELECT 'Africa' area,'india' country ) SELECT CASE WHEN Area IN ('Asia','europe') THEN Area ELSE 'spark' END AS AreaName,COUNT(1) country_num FROM t1 GROUP BY CASE WHEN Area IN ('Asia','europe') THEN Area ELSE 'spark' end

或者也可以反過來用 not in
;WITH t1 AS ( SELECT 'Asia' Area,'china' country UNION all SELECT 'Asia' Area,'russia' country UNION all SELECT 'europe' Area,'england' country UNION all SELECT 'europe' Area,'germany' country UNION all SELECT 'Africa' area,'india' country ) SELECT CASE WHEN Area NOT IN ('Asia','europe') THEN 'spark' ELSE Area END AS AreaName,COUNT(1) country_num FROM t1 GROUP BY CASE WHEN Area NOT IN ('Asia','europe') THEN 'spark' ELSE Area end

【3】關於分數計數的案例
需求:

解決:
WITH t1 AS ( SELECT 'a' as name,100 score UNION all SELECT 'b' ,99 score UNION all SELECT 'c' ,80 score UNION all SELECT 'd' ,59 score UNION all SELECT 'e' ,40 score ) select case when score >=90 then '優秀' when score >=80 then '良好' when score >=60 then '及格' else '不及格' end ,count(1) as num FROM t1 group by score ---------------------------------------------------------- ;WITH t1 AS ( SELECT 'a' as name,100 score UNION all SELECT 'b' ,99 score UNION all SELECT 'c' ,80 score UNION all SELECT 'd' ,59 score UNION all SELECT 'e' ,40 score ) select case when score >=90 then '優秀' when score >=80 then '良好' when score >=60 then '及格' else '不及格' end ,count(1) as num FROM t1 group by case when score >=90 then '優秀' when score >=80 then '良好' when score >=60 then '及格' else '不及格' end

第二段代碼正確,實現了我們的需求
