案例來源:PTT

Name Product
--- ---
陳一 1
陳一 1
陳一 2
李二 2 輪胎:1、茶杯:2

統計報表想呈現如下:

姓名 輪胎 茶杯
--- --- ---
陳一 2 1
李二 0 1

 

解法:  case 搭配 sum or count

1.case 搭配 sum

select name,sum(case when product=1 then 1 else 0 end)"輪胎"
,sum(case when product=2 then 1 else 0 end)"茶杯"
from table2 group by name;

 

2.case 搭配 count

select name,count(case when product=1 then product else null end)"輪胎" 
,count(case when product=2 then product else null end)"茶杯"
from table2 group by name;

 

 

 

 

 

 

 

文章標籤
全站熱搜
創作者介紹
創作者 to52016 的頭像
to52016

Eason [資料科學//Python學習/資料庫] & [拍片&剪片]

to52016 發表在 痞客邦 留言(0) 人氣(166)