SQL创建列从值并填充其他列

时间:2013-09-05 13:04:29

标签: mysql sql pivot

我想从1列中获取值,然后将它们转换为另一列的标题。它更容易告诉你:

初始表:

Name      | Label   | Value
Tom Jones | January | 42
Rick James| March   | 83

结束表:

Name      | January | March
Tom Jones | 42      | NULL
Rick James| NULL    | 83

由于我在Label上进行的排序和排序类型,因此需要这样的格式。

更新: 当我提到多列值时,我的意思是:

Name      | Label_1   | ValueA_1 | ValueB_1 | Label_2 | ValueA_2 | ValueB_2
Tom Jones | January   | 42       | 77       | March   | 99       | 22
Rick James| March     | 83       | 17       | May     | NULL     | 112

1 个答案:

答案 0 :(得分:1)

使用CREATE TABLE NewTable AS SELECT ...

CREATE TABLE newTable
SELECT
  NAme, 
  SUM(CASE WHEN Label = 'January' THEN value  END) AS January,
  SUM(CASE WHEN Label = 'March' THEN value END) AS March
FROM tablename AS t1
GROUP BY Name;

这将创建一个全新的表newTable,其结构与SELECT语句相同。


<强>更新

根据您的评论,如果您想获得value逗号分隔的值:

CREATE TABLE newTable
SELECT
  Name, 
  GROUP_CONCAT(CASE WHEN Label = 'January' THEN value  END) AS January,
  GROUP_CONCAT(CASE WHEN Label = 'March' THEN value  END) AS March
FROM table1 AS t1
GROUP BY Name;

更新

如果你想动态地执行此操作,而不是硬编码值,则必须使用动态sql来执行此操作,如下所示:

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT CONCAT('GROUP_CONCAT(IF(Label = ''',
      Label, ''', value, NULL)) AS ', '''', Label , '''')
  ) INTO @sql
FROM Table1 ;

SET @sql = CONCAT('CREATE TABLE newTable ',
                  'SELECT Name,' ,
                  @sql, ' FROM table1 ',
                  ' GROUP BY Name');


prepare stmt 
FROM @sql;

execute stmt;

Updated SQL Fiddle Demo