Oracle case when then簡單用法

rowid      ID 主鍵     COUNTRY 國家    SEX 性別    POPULIATION 人口數量sql

1     0     中國     1     200 code

2     1     中國     2     300 io

3     2     美國     1     20 class

4     3     美國     2     10 test

5     4     加拿大     1     40 select

6     5     加拿大     2     80 co

7     6     英國     1     55 cas

8     7     英國     2     110 

9     8     小日本     3     111 

select t.country,
sum(case 
       when t.sex = '1' then t.populiation else '0' end) as 男,
sum(case when t.sex = '2' then t.populiation else '0' end) as 女
from test t group by t.country

rowid   country  男   女

1 中國 200 300
2 加拿大 40 80
3 美國 20 10
4 小日本 0 0
5 英國 55 110

select sum(t.populiation) ,
 case t.country when '中國' then '亞洲' when '美國' then '美洲'
       when '加拿大' then '美洲' when '英國' then '歐洲' 
      else '其餘' end 
from test t  GROUP BY CASE t.country
     WHEN '中國'     THEN '亞洲'  WHEN '美國'     THEN '美洲' 
     WHEN '加拿大' THEN '美洲'  WHEN '英國' THEN '歐洲' ELSE '其餘' END;

rowid   sum       area

1 165 歐洲2 111 其餘3 500 亞洲4 150 美洲

相關文章
相關標籤/搜索