在“单行”中为多个列选择不同的值

时间:2013-09-02 07:48:22

标签: sql sql-server sql-server-2008 tsql

我有一个名为“计算”的SQL表,如下所示:

id | InsulationMaterialId1 | InsulationMaterialId2| InsulationMaterialId3 | InsulationMaterialId4
-----------------------
1  | 34 | 45 | 34 | 50
2  | 34 | 78 | 35 | 51
3  | 35 | 32 | 34 | 52
4  | 36 | 30 | 34 | 53
5  | 40 | 39 | 34 | 34
6  | 41 | 34 | 34 | 56
7  | 42 | 36 | 34 | 53

在这些表中,我们有4列带有绝缘ID,我希望在一个单独的列中使用','分隔的方式获得独特的绝缘ID输出如下: -

 id | InsulationMaterialIds 
-----------------------
1  | 34,45,50
2  | 34,78,35,51
3  | 35,32,34,52
4  | 36,30,34,53
5  | 40,39,34
6  | 41,34,56
7  | 42,36,34,53

1 个答案:

答案 0 :(得分:6)

<强> DDL:

DECLARE @temp TABLE
(
      id INT
    , InsulationMaterialId1 INT
    , InsulationMaterialId2 INT
    , InsulationMaterialId3 INT
    , InsulationMaterialId4 INT
)

INSERT INTO @temp (id, InsulationMaterialId1, InsulationMaterialId2, InsulationMaterialId3, InsulationMaterialId4)
VALUES 
    (1, 34, 45, 34, 50),(2, 34, 78, 35, 51),
    (3, 35, 32, 34, 52),(4, 36, 30, 34, 53),
    (5, 40, 39, 34, 34),(6, 41, 34, 34, 56),(7, 42, 36, 34, 53)

#1:使用PIVOT查询

;WITH cte AS (
    SELECT id, InsulationMaterialId 
    FROM @temp
    UNPIVOT 
    (
        InsulationMaterialId FOR tt IN (
            InsulationMaterialId1, 
            InsulationMaterialId2, 
            InsulationMaterialId3, 
            InsulationMaterialId4
        )
    ) unpvt
)
SELECT 
    t.id, 
    InsulationMaterialIds = STUFF((
        SELECT DISTINCT ',' + CAST(InsulationMaterialId AS VARCHAR(10))
        FROM cte t2
        WHERE t.id = t2.id
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(100)'), 1, 1, '')     
FROM (
    SELECT DISTINCT id 
    FROM @temp
) t

#2:没有PIVOT查询(比#1快)

SELECT 
    id, 
    InsulationMaterialIds = STUFF((
        SELECT DISTINCT ',' + CAST(InsulationMaterialId AS VARCHAR(10))
        FROM (
            VALUES 
                (InsulationMaterialId1),
                (InsulationMaterialId2),
                (InsulationMaterialId3),
                (InsulationMaterialId4)
        ) t2(InsulationMaterialId)
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(100)'), 1, 1, '')     
FROM @temp

<强>输出:

id          InsulationMaterialIds
----------- ---------------------
1           34,45,50
2           34,35,51,78
3           32,34,35,52
4           30,34,36,53
5           34,39,40
6           34,41,56
7           34,36,42,53