sql在group by 中使用case when
阿新 • • 發佈:2020-08-07
【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 AreaWHEN 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