SQL Server:多个记录合并到具有相同ID的同一行

时间:2014-02-27 09:31:06

标签: sql-server

我的桌子看起来像这样:

P_ID    Lang   
1001    EN
1001    German 

期待结果:

P_ID Lang1  Lang2  
1001  EN     German

2 个答案:

答案 0 :(得分:1)

只是必须像这样做PIVOT,所以这里是根据您的具体情况修改我的代码:

SELECT * FROM
(
    SELECT P_ID,
           Lang,
           NumberedLang = 'Lang' + CAST(ROW_NUMBER() OVER 
               (PARTITION BY P_ID ORDER BY Lang) AS NVARCHAR(100))               
    FROM   YourTableName   
) AS OrderLangs
PIVOT (MAX(Lang) FOR NumberedLang IN (Lang1, Lang2)) AS PivotedLangs

以下是SQL Fiddle,告诉您它有效。

如果您不想指定所有不同的NumberedLang值,则必须使用“动态”枢轴,您可以在其中执行基于文本的SQL中的所有代码。由于没有可用的查询计划,它们可能效率很低。

答案 1 :(得分:0)

这有点难看,但你可以这样做:

select p_id
, max( case when langNum=1 then lang else null end ) as Lang1
, max( case when langNum=2 then lang else null end ) as Lang2
, max( case when langNum=3 then lang else null end ) as Lang3
, max( case when langNum=4 then lang else null end ) as Lang4
, max( case when langNum=5 then lang else null end ) as Lang5
-- ...
from ( 
    select p_id
      , lang
      -- Get a number for each row, starting from 1 for each p_id:
      , row_number() over ( partition by p_id order by lang ) as LangNum
    from theTable
) as x
group by p_id