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