行到列mysql

时间:2014-09-19 20:48:09

标签: mysql pivot

我有一个包含1000个城市的表,它们在第1天...第30天报告3个环境变量(variable1,variable2,variable3)。这是一个示例表。

create table myTable1 (dt date, City varchar(15), type varchar(10), 
                       Day1 int, Day2 int, Day3 int);

insert into myTable1 values
('2014-09-19','Toronto','Variable1', 100,90,80),
('2014-09-19','Toronto','Variable2', 20,15,10),
('2014-09-19','Toronto','Variable3', 3,2,1),
('2014-09-19','Chicago','Variable1', 999,888,777),
('2014-09-19','Chicago','Variable2', 500,400,300),
('2014-09-19','Chicago','Variable3', 300,250,200);

我想操纵它,所以最终的结果是在以下结构中。我想要一个新列 Day ,它将当天的值(即1,2 ... 30)和名为 type 的列中的值变为列(所以3列称为Variable1,Variable2,Variable3)。

dt, City, Day, Variable1, Variable2, Variable3
2014-09-19, Toronto, 1, 100, 20, 3
2014-09-19, Toronto, 2, 90, 15,2
2014-09-19, Toronto, 3, 80, 10, 1
2014-09-19, Chicago, 1, 999,500,300
2014-09-19, Chicago, 2, 888,400, 250
2014-09-19, Chicago, 3, 777,300,200

我知道我可以根据unpivot row values into multple columns中的解决方案在sql server中执行此操作。由于mySQL没有透视/非透视,我不知道如何做到这一点。我在下面的小提琴演示中修改了一些代码,但它并没有完全符合我的要求。我感谢您的帮助。

http://sqlfiddle.com/#!2/91176/2

1 个答案:

答案 0 :(得分:2)

这是一个复杂的条件聚合:

select t.dt, t.city, d.day,
       max(case when d.day = 1 and t.type = 'Variable1' then day1
                when d.day = 2 and t.type = 'Variable1' then day2
                when d.day = 3 and t.type = 'Variable1' then day3
           end) as Variable1,
       max(case when d.day = 1 and t.type = 'Variable2' then day1
                when d.day = 2 and t.type = 'Variable2' then day2
                when d.day = 3 and t.type = 'Variable2' then day3
           end) as Variable2,
       max(case when d.day = 1 and t.type = 'Variable3' then day1
                when d.day = 2 and t.type = 'Variable3' then day2
                when d.day = 3 and t.type = 'Variable3' then day3
           end) as Variable3                
from mytable1 t cross join
     (select 1 as day union all select 2 union all select 3) d
group by t.dt, t.city, d.day;

您可以在SQL小提琴中看到这项工作。