简体   繁体   English

行到列mysql

[英]rows to columns mysql

I have a table with 1000 cities that report 3 environmental variables (variable1, variable2, variable3) on day1...day30. 我有一张包含1000个城市的表格,在第1天...第30天报告3个环境变量(变量1,变量2,变量3)。 Here is an example table. 这是一个示例表。

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);

I want to manipulate it so the final result is in the following structure. 我想对其进行操作,以便最终结果为以下结构。 I want a new column, Day that takes the value of the day (ie 1, 2 ... 30) and the values inside the column named type to become columns (so 3 columns called Variable1, Variable2, Variable3). 我想要一个新列Day ,它采用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

I know I can do this in sql server as per the solution in unpivot row values into multple columns . 我知道我可以在SQL Server中按照将数据透视表中的行值解开成多个列的解决方案来执行此操作。 Since mySQL doesn't have pivot/unpivot I'm not sure how to do this. 由于mySQL没有枢轴/不枢轴,因此我不确定如何执行此操作。 I have tinkered with some code in the following fiddle demo but it doesn't quite do what I want it to do. 在下面的小提琴演示中,我已经修改了一些代码,但是它并没有完全实现我想要的功能。 I appreciate your help. 我感谢您的帮助。

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

This is a complicated conditional aggregation: 这是一个复杂的条件聚合:

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;

You can see this work in your SQL Fiddle. 您可以在SQL Fiddle中看到这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM