首页 > 技术文章 > sql的case when then else end 的语法实现列转行

YuyuanNo1 2018-02-01 14:21 原文

SELECT * FROM test5 ;

RESOURCES DATETIME CNT ID
1 0 2018-01-22 4 1
2 0 2018-01-24 10 2
3 0 2018-01-25 25 3
4 0 2018-01-26 14 4
5 0 2018-01-29 3 5
6 1 2018-01-29 22 6
7 2 2018-01-29 1 7
8 1 2018-01-30 44 8
9 2 2018-01-30 7 9
10 2 2018-01-31 1 10
11 2 2018-02-01 1 11

、、、、、、、、、、、、

SELECT datetime, sum(case when resources=0 then cnt else null end) as anzhuo,
sum(case when resources=1 then cnt else null end) as ios,
sum(case when resources=2 then cnt else null end) as houtai
FROM test5 t
group by t.datetime
;

、、、、、、、、、、、、、、

DATETIME ANZHUO IOS HOUTAI
1 2018-01-25 25
2 2018-01-24 10
3 2018-01-26 14
4 2018-01-31 1
5 2018-01-30 44 7
6 2018-01-29 3 22 1
7 2018-01-22 4
8 2018-02-01 1

 

推荐阅读