连接2列或更多列的多行

时间:2015-11-19 01:14:40

标签: sql sql-server tsql

我找到了连接单个列的多行的示例,但是我在将它应用于两列或更多列时遇到了困难。以下是该表的示例:

ID  Col1    Col2    Col3
1   1A      2A      1
2   1B      2B      2
2   1C      2C      3
3   1D      2D      4
3   1E      2E      5

期望的结果:

ID  Col1    Col2    Col3
1   1A      2A      AGGREGATE such as MIN
2   1B,1C   2B,2C   "
3   1D,1E   2D,2E   "

我怎么能完成上述?感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用XML PATH来实现此目标

示例数据

DECLARE @tbl TABLE(ID INT,Col1 VARCHAR(5),Col2 VARCHAR(5),Col3 INT)

INSERT @tbl
SELECT 1, '1A', '2A', 1 UNION
SELECT 2, '1B', '2B', 2 UNION
SELECT 2, '1C', '2C', 3 UNION
SELECT 3, '1D', '2D', 4 UNION
SELECT 3, '1E', '2E', 5

使用XML PATH

SELECT tbl.ID
       ,LEFT(tbl.Col1, LEN(tbl.Col1) - 1) AS Col1
       ,LEFT(tbl.Col2, LEN(tbl.Col2) - 1) AS Col2
       ,Col3
FROM(SELECT DISTINCT sub2.ID
                    ,(SELECT sub.Col1 + ',' AS [text()]
                      FROM @tbl AS sub
                      WHERE sub.ID = sub2.ID
                      ORDER BY sub.ID
                      FOR XML PATH ('')
                    ) AS Col1
                    ,(SELECT sub.Col2 + ',' AS [text()]
                     FROM @tbl AS sub
                     WHERE sub.ID = sub2.ID
                     ORDER BY sub.ID
                     FOR XML PATH ('')
                    ) AS Col2
                    ,(SELECT MIN(Col3)
                      FROM @tbl AS sub
                      WHERE sub.ID = sub2.ID
                      GROUP BY ID
                     ) AS Col3
     FROM @tbl sub2
) AS tbl

<强>输出

ID  Col1    Col2    Col3
1   1A      2A      1
2   1B,1C   2B,2C   2
3   1D,1E   2D,2E   4

答案 1 :(得分:0)

试试这个,

SELECT DISTINCT A.ID,
                Stuff((SELECT DISTINCT ',' + A1.COL_1
                       FROM   #YOUR_TABLE A1
                       WHERE  A.ID = A1.ID
                       FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') TEMP_1,
                Stuff((SELECT DISTINCT ',' + A1.COL_2
                       FROM   #YOUR_TABLE A1
                       WHERE  A.ID = A1.ID
                       FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') TEMP_2,
                (SELECT Min(COL_3)
                 FROM   #YOUR_TABLE A1
                 WHERE  A.ID = A1.ID
                 GROUP  BY ID)                                                        AS COL_3
FROM   #YOUR_TABLE A;