在Mysql中将表转换为特定格式

时间:2013-03-20 23:07:59

标签: mysql sql database relational-database

我有一张170万行的表。 表结构是(Datapoint,AttributeName,AttributeValue)。

First column i.e Datapoint is like :
(1,AttributeName1,Attributevalue1)
(1,AttributeName2.Attributevalue2)
.
.
n times
(2,AttributeName1,Attributevalue1)
(2,AttributeName2,Attributevalue2)
.
.
m times
(11113,AttributeName1,Attributevalue1)
(11113,AttributeName2,Attributevalue2)
.
.
ptimes

我需要在SQL中编写一个过程,将上述数据转换为以下格式:

(Datapoint,AttributeName1,AttributeName2,.............AttributeNamen)
(1,       ,AttributeValue1,AttributeValue2,.........................)
(2,       ,AttributeValue1,AttributeValue2,.........................)

(11113,   ,AttributeValue1,AttributeValue2,.........................)

请让我知道如何去做。 感谢

1 个答案:

答案 0 :(得分:1)

MySQL没有 pivot 函数,但您可以使用带有CASE表达式的聚合函数将数据从行转换为列:

select datapoint,
  max(case when AttributeName ='AttributeName1' then AttributeValue end) as AttributeName1,
  max(case when AttributeName ='AttributeName2' then AttributeValue end) as AttributeName2,
  max(case when AttributeName ='AttributeName3' then AttributeValue end) as AttributeName3,
  max(case when AttributeName ='AttributeName4' then AttributeValue end) as AttributeName4
from yourtable
group by datapoint

如果您拥有已知数量的值,则上述版本将非常有用。但是,如果要将未知数量的项转换为列,则需要使用预准备语句来生成动态SQL。您应该查看以下文章:

Dynamic pivot tables (transform rows to columns)

代码与此类似:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(CASE WHEN AttributeName = ''',
      AttributeName,
      ''' THEN AttributeValue END) AS `',
      AttributeName, '`'
    )
  ) INTO @sql
FROM yourtable;


SET @sql 
  = CONCAT('SELECT datapoint, ', @sql, ' 
           from yourtable
           group by datapoint');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
相关问题