1

我有一个名为“计算”的 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
4

1 回答 1

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
于 2013-09-02T07:53:30.490 回答