在mysql中将行创建为列

时间:2015-09-03 06:50:22

标签: mysql sql

我有这个小时明智的数据,我想生成报告,我必须按产品,模式,区域(抱歉格式不好)的每一行显示每小时的收入

      price  product   mode             region         HOUR 

1.     0     p1        direct            reg1          1 
2.     10    p3        indirect          reg2          2 
3.     0     p2        direct            reg1          1 
4.     0     p1        indirect          reg2          2 
5.     0     p2        direct            reg5          3 
6.     0     p1        direct            reg1          3 
7.     0     p1        direct            reg2          3 
8.     0     p3        indirect          reg4          17 
9.     0     p4        direct            reg2          17 
10.    21    p1        direct            reg2          17 


        HOUR1 HOUR2 HOUR3 HOUR4 HOUR5....HOUR23 product   mode    region
  1.    0      10     1     30                  p1     direct       reg1
  2.    0      5      1     10                  p1     indirect     reg2

1 个答案:

答案 0 :(得分:0)

不幸的是,mysql没有任何内置的pivot功能,所以你需要为未知的pivot元素集编写一个动态sql,或者可以使用最常用的pivot生成技术来处理已知的pivot元素集,在你的情况下它是已知集合,因为您正在查看从第1小时到第23小时的数据透视数据,它可以作为

完成
select
sum( case when HOUR = 1 then price else 0 end) as `HOUR1`,
sum( case when HOUR = 2 then price else 0 end) as `HOUR2`,
sum( case when HOUR = 3 then price else 0 end) as `HOUR3`,
sum( case when HOUR = 4 then price else 0 end) as `HOUR4`,
sum( case when HOUR = 5 then price else 0 end) as `HOUR5`,
sum( case when HOUR = 6 then price else 0 end) as `HOUR6`,
sum( case when HOUR = 7 then price else 0 end) as `HOUR7`,
sum( case when HOUR = 8 then price else 0 end) as `HOUR8`,
sum( case when HOUR = 9 then price else 0 end) as `HOUR9`,
sum( case when HOUR = 10 then price else 0 end) as `HOUR10`,
sum( case when HOUR = 11 then price else 0 end) as `HOUR11`,
sum( case when HOUR = 12 then price else 0 end) as `HOUR12`,
sum( case when HOUR = 13 then price else 0 end) as `HOUR13`,
sum( case when HOUR = 14 then price else 0 end) as `HOUR14`,
sum( case when HOUR = 15 then price else 0 end) as `HOUR15`,
sum( case when HOUR = 16 then price else 0 end) as `HOUR16`,
sum( case when HOUR = 17 then price else 0 end) as `HOUR17`,
sum( case when HOUR = 18 then price else 0 end) as `HOUR18`,
sum( case when HOUR = 19 then price else 0 end) as `HOUR19`,
sum( case when HOUR = 20 then price else 0 end) as `HOUR20`,
sum( case when HOUR = 21 then price else 0 end) as `HOUR21`,
sum( case when HOUR = 22 then price else 0 end) as `HOUR22`,
sum( case when HOUR = 23 then price else 0 end) as `HOUR23`,
product,
mode,
region
from mytable 
group by product,mode,region;

http://sqlfiddle.com/#!9/b2e868/1