SQL case when的使用實例
數據表:CaseWhen
ID |
website1 |
website2 |
website3 |
Name |
1 |
null |
www.mozhenlong.com |
www.mozhenlong.xin |
mzl |
2 |
www.baidu.com |
www.mozhenlong.com |
null |
mzl1 |
3 |
null |
null |
www.mozhenlong.xin |
mzl |
4 |
null |
www.mozhenlong.com |
null |
mzl1 |
5 |
www.baidu.com |
null |
www.mozhenlong.xin |
mzl |
6 |
null |
www.mozhenlong.com |
null |
mzl1 |
7 |
null |
www.mozhenlong.com |
www.mozhenlong.xin |
mzl |
8 |
null |
www.mozhenlong.com |
null |
mzl1 |
9 |
www.baidu.com |
www.mozhenlong.com |
nill |
mzl |
10 |
null |
null |
www.mozhenlong.xin |
mzl2 |
11 |
null |
www.mozhenlong.com |
null |
mzl |
12 |
www.baidu.com |
www.mozhenlong.com |
null |
mzl2 |
13 |
null |
null |
www.mozhenlong.xin |
mzl2 |
14 |
null |
null |
www.mozhenlong.xin |
mzl3 |
統計每個用戶訪問各個站點的總數:
使用case when查詢語句:
select Name,
SUM(case website1 when 'www.baidu.com' then 1 else 0 end) as BaiduPost,
SUM(case website2 when 'www.mozhenlong.com' then 1 else 0 end) as MzlComPost,
SUM(case website3 when 'www.mozhenlong.xin' then 1 else 0 end) as MzlXinPost
from CaseWhen
group by Name
order by Name
使用IIF查詢語句:
select Name,
SUM(IIF(website1 = 'www.baidu.com',1,0) as BaiduPost,
SUM(IIF(website2 = 'www.mozhenlong.com',1,0) as MzlComPost,
SUM(IIF(website3 = 'www.mozhenlong.xin',1,0) as MzlXinPost
from CaseWhen
group by Name
order by Name
統計結果:
Name |
BaiduPost |
MzlComPost |
MzlXinPost |
mzl |
2 |
4 |
4 |
mzl1 |
1 |
4 |
0 |
mzl2 |
1 |
1 |
2 |
mzl3 |
0 |
1 |
1 |