Mysql 列轉行
阿新 • • 發佈:2018-11-12
SQL 開發案例
Mysql 列轉行
第一篇 試著 發一下
表結構 create table t1 ( day varchar(8), registercount int, logincount int ) 插入語句 insert into t1 values ('20120101' ,1,4 ) ; insert into t1 values ('20120102' ,2,5 ) ; insert into t1 values ('20120103' ,3,6 ) ; Current database: test +----------+---------------+------------+-----+ | day | registercount | logincount | 1 | +----------+---------------+------------+-----+ | 20120101 | 1 | 4 | 1 | | 20120101 | 1 | 4 | 2 | | 20120102 | 2 | 5 | 1 | | 20120102 | 2 | 5 | 2 | | 20120103 | 3 | 6 | 1 | | 20120103 | 3 | 6 | 2 | +----------+---------------+------------+----+ List item 6 rows in set (0.01 sec) select case when t.a = '1' then 'registercount' when t.a = '2' then 'logincount' end type , min(case when t1.day = '20120101' and t.t.a = '1' then t1.registercount when t1.day = '20120101' and t.t.a = '2' then t1.logincount end ) d20120101 ,min(case when t1.day = '20120102' and t.t.a = '1' then t1.registercount when t1.day = '20120102' and t.t.a = '2' then t1.logincount end) d20120102 ,min(case when t1.day = '20120103' and t.t.a = '1' then t1.registercount when t1.day = '20120103' and t.t.a = '2' then t1.logincount end ) d20120103 from t1 ,(select 1 a union all select 2 ) t group by case when t.a = '1' then 'registercount' when t.a = '1' then 'logincount' end ;