sql server在group by 中使用 case when


【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

  

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM