2012-11-15 21 views
4

任何人都可以帮助我有一个表格,其中包含一些植物记录。一个工厂可以有多个名称,表格将这些名称显示为不同的记录。该表被称为new_plantsname将具有相同ID的行组合到保持所有数据的一行中

plantid name 
1  tree 
1  rose 
2  bush 
3  tree 
3  bush 
3  rose 

这个持续了3000条记录

我想它是什么,以合并记录有相同plantid,并显示在不同列中的不同的名字:

plantid name1 name2 name3 ... 
1  tree rose NULL 
2  shrub NULL NULL 
3  tree rose bush 

可以帮我查询吗?我也希望结果保存到一个新的表提前

感谢

+0

将'选择由plantid'从new_plantsname组GROUP_CONCAT(名字)吗? (假设MySQL) –

+0

找到植物的最大ID并使用PIVOT有用吗? –

回答

4

这基本上是一个PIVOT(没有指定RDBMS),我假定MySQL和它没有一个PIVOT功能,因此您需要用CASE语句使用聚合函数复制此内容。该解决方案为每行添加rownumber,因此您可以确定需要将多少个name转换为列。

如果你知道你要多少name值有你可以硬编码值:

select plantid, 
    max(case when nameRn = 'name1' then name end) Name1, 
    max(case when nameRn = 'name2' then name end) Name2, 
    max(case when nameRn = 'name3' then name end) Name3 
from 
(
    select plantid, name, 
     concat('name', @num := if(@plantid = `plantid`, @num + 1, 1)) as nameRn, 
     @plantid := `plantid` as dummy 
    from 
    (
    select plantid, name, @rn:[email protected]+1 overall_row_num 
    from yourtable, (SELECT @rn:=0) r 
) x 
    order by plantid, overall_row_num 
) src 
group by plantid; 

SQL Fiddle with Demo

如果你有一个未知的数值,那么你可以使用一份声明中产生的这种动态的版本:

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'max(case when nameRn = ''', 
     nameRn, 
     ''' then name end) AS ', 
     nameRn 
    ) 
) INTO @sql 
FROM 
(
    select plantid, name, 
     concat('name', @num := if(@plantid = `plantid`, @num + 1, 1)) as nameRn, 
     @plantid := `plantid` as dummy 
    from 
    (
    select plantid, name, @rn:[email protected]+1 overall_row_num 
    from yourtable, (SELECT @rn:=0) r 
) x 
    order by plantid, overall_row_num 
) src; 


SET @sql = CONCAT('SELECT plantid, ', @sql, ' 
        FROM 
        (
        select plantid, name, 
         concat(''name'', @num := if(@plantid = `plantid`, @num + 1, 1)) as nameRn, 
         @plantid := `plantid` as dummy 
        from 
        (
         select plantid, name, @rn:[email protected]+1 overall_row_num 
         from yourtable, (SELECT @rn:=0) r 
        ) x 
        order by plantid, overall_row_num 
       ) src 
        GROUP BY plantid'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

SQL Fiddle with Demo

两者都会产生相同的结果:

| PLANTID | NAME1 | NAME2 | NAME3 | 
------------------------------------- 
|  1 | tree | rose | (null) | 
|  2 | bush | (null) | (null) | 
|  3 | tree | bush | rose | 
+0

感谢这是伟大的会投票答案,但新的网站,所以不能但 – zaratjlc

+0

我这样做的虾米phpmyadmin并获得一个错误:#1243 - 未知的准备语句处理程序(stmt)给予EXECUTE – zaratjlc

+0

@zaratjlc我无法重现你说你得到的错误。 – Taryn

相关问题