SQL pivot 1:M行到字符串列

时间:2017-07-05 18:19:21

标签: sql sql-server tsql

我有一个1:M记录集,我需要将其转换为连接结果的列。

创建样本数据:

CREATE TABLE #temptable 
(
    ID int,
    Division int,
    Material int
);

 insert into #temptable
 Values
 (999, 1, 1)
 ,(999, 1, 2)
 ,(999, 1, 3)
 ,(999, 2, 1)
 ,(999, 2, 6)
 ,(999, 3, 2)

示例数据:

ID     Division     Material   
----  ----------   ----------   
999       1            1          
999       1            2
999       1            3
999       2            1
999       2            6
999       3            2

我需要将结果看起来像这样,每个部门的材料连接在一起:

 ID   Division-1   Division-2   Division-3
----  ----------   ----------   ----------
999     1,2,3          1,6          2

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ID,
       [1] AS 'Division-1',
       [2] AS 'Division-2',
       [3] AS 'Division-3'
FROM
(
    SELECT DISTINCT
           a.ID,
           a.Division,
           LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
    FROM #temptable a
         CROSS APPLY
    (
        SELECT CAST(Material AS VARCHAR(10))+','
        FROM #temptable t
        WHERE a.[ID] = t.[ID]
              AND a.Division = t.Division
        FOR XML PATH('')
    ) r(ResourceName)
) src PIVOT(MAX(ResourceName) FOR Division IN([1],
                                              [2],
                                              [3])) piv; 

简要说明 我们需要在逗号分隔结构上创建数据透视。

以下查询将列值转换为逗号分隔的行。

SELECT a.ID,
       a.Division,
       LEFT(r.ResourceName, LEN(r.ResourceName) - 1) ResourceName
FROM #temptable a
     CROSS APPLY
(
    SELECT CAST(Material AS VARCHAR(10))+','
    FROM #temptable t
    WHERE a.[ID] = t.[ID]
          AND a.Division = t.Division
    FOR XML PATH('')
) r(ResourceName);

之后我们在它上面创建支点。