2013-03-20 61 views
-4

我有一个包含170万行的表。 表结构是(Datapoint,AttributeName,AttributeValue)。在Mysql中将表转换为特定格式

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,.........................)

请让我知道如何去了解它。 感谢

+0

请注明您已经尝试了什么。 – ronak 2013-03-20 23:09:33

+0

搜索“mysql pivot”或“mysql rows to columns” – Kermit 2013-03-20 23:10:09

回答

1

MySQL没有一个支点功能,但可以使用聚合函数与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; 
+0

我需要概括一下,就像你在第二个方法中做的那样。但是我不清楚代码,你能告诉我从哪里可以阅读更多关于以上让我明白发生了什么事? – 2013-03-20 23:29:36

+0

@SahilMadan我编辑了我的答案,并链接到一篇文章,但是这里是链接 - http://buysql.com/mysql/14-how-to-automate-pivot-tables.html – Taryn 2013-03-20 23:31:56

+0

非常感谢!我了解它是如何工作的。该过程正在执行没有任何错误。但是在“PREPARE stmt FROM @sql”中有一些语法错误。不知道它是什么。对此有任何想法? – 2013-03-20 23:51:38

相关问题