Tsql所有id和值在一行中

时间:2016-04-04 11:59:32

标签: sql sql-server tsql aggregate

如何在一行中选择所有ID和值,按条件分组?

例如:

| id | value | condition |
--------------------------
| 1 | value1 |     0     |
| 2 | value2 |     0     |
| 3 | value3 |     1     |
| 4 | value4 |     1     |

结果:

| ids  |     values     | condition |
-------------------------
| 1, 2 | value1, value2 |     0     |
| 3, 4 | value3, value4 |     1     |

1 个答案:

答案 0 :(得分:0)

试试这样:

CREATE TABLE #test(id INT,value VARCHAR(100),condition INT);
INSERT INTO #test VALUES
 (1,'value1',0)
,(2,'value2',0)
,(3,'value3',1)
,(4,'value4',1);

WITH MyDistinctConditions AS
(
    SELECT DISTINCT condition
    FROM #test 
)
SELECT c.condition
      ,(SELECT STUFF(
                      (
                      SELECT ', ' + CAST(t.id AS VARCHAR(10)) 
                      FROM #test AS t 
                      WHERE t.condition=c.condition
                      FOR XML PATH('')),1,2,'')) AS ids
      ,(SELECT STUFF(
                      (
                      SELECT ', ' + t.value 
                      FROM #test AS t 
                      WHERE t.condition=c.condition
                      FOR XML PATH('')),1,2,'')) AS [values]
FROM MyDistinctConditions AS c;

DROP TABLE #test;

结果

condition   ids     values
0           1, 2    value1, value2
1           3, 4    value3, value4