MYSQL转置列(rowsto列)

时间:2016-08-23 04:45:18

标签: mysql

我有一个表格tab1,如下所示

date_part   hour_part   Country     name    Name_value
7/29/2016      0         US         abc      10.3
7/29/2016      1         US         abc      10.2
7/29/2016      2         US         abc      10
7/29/2016      0        France      xyz      2.1
7/29/2016      1        France      xyz      2.12
7/29/2016      2        France      xyz      2.18
7/29/2016      3        France      xyz      2.04
7/30/2016      7        UK          bbb      11
7/30/2016      8        UK          bbb      11.2
7/30/2016      9        UK          bbb      11.5
7/30/2016     10        UK          bbb      11.7

现在如何从tab1获取tab2,如下所示

date_part   hour_part    country    abc       xyz       bbb
7/29/2016   0             US       10.3     
7/29/2016   1             US       10.2     
7/29/2016   2             US       10       
7/29/2016   0           France                2.1   
7/29/2016   1           France                2.12  
7/29/2016   2           France                2.18  
7/29/2016   3           France                2.04  
7/30/2016   7           UK                               11
7/30/2016   8           UK                               11.2
7/30/2016   9           UK                               11.5
7/30/2016   10          UK                               11.7

提前致谢

1 个答案:

答案 0 :(得分:0)

使用透视查询:

SELECT date_part,
       hour_part,
       country,
       CASE WHEN name = 'abc' THEN Name_value ELSE 0 END AS abc,
       CASE WHEN name = 'xyz' THEN Name_value ELSE 0 END AS xyz,
       CASE WHEN name = 'bbb' THEN Name_value ELSE 0 END AS bbb
FROM tab1

请注意,您没有告诉我们您希望在abcxyzbbb列中使用哪些值作为空占位符。我在上面的查询中使用了零,但是如果你想要可以为空的列,你也可以使用NULL(或者实际上是任何其他数值)。