Mysql 列转行

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
;

猜你喜欢

转载自blog.csdn.net/qidan3500/article/details/82799896