Return columns as comma separated, for more than one condition on key or more than one row
I have a table with values:
Key1 Key2 ColumnKey
1 idx here
1 idx there
2 idx where
2 idx why
I need to return, for both Key1, Key2 being same, columnKey separated by commas.
Example: Instead of
1 idx here
1 idx there
Need to return
1 idx here, there
Query that works:
DECLARE @commaSeperatedRes NVARCHAR(MAX);
SELECT @commaSeperatedRes = COALESCE(@commaSeperatedRes + ', ', '') + ColumnKey
FROM Table1
WHERE Table1.Key1= 1 AND Table1.Key2 = 'idx';
print @commaSeperatedRes
Problem is, I need to return this for more than one row:
1 idx here, there
2 idx where, why
DECLARE @commaSeperated NVARCHAR(MAX);
SELECT @commaSeperatedRes = CO开发者_运维技巧ALESCE(@commaSeperated + ', ', '') + ColumnKey
FROM Table1
WHERE (Table1.Key1= 1 and Table1.Key2 = 'idx')
OR
( Table1.Key1 = 2 Table1.Key2 = 'idx')
print @commaSeperatedRes
Also, I will insert these results into a temporary table so the values are clubbed with some more columns from other tables. Ideally, my temporary table that I'll work with should look like this:
TKey1 TKey2 TColumnKey
1 idx here, there
2 idx where, why
SELECT t1.Key1, t1.Key2,
STUFF((SELECT ', ' + ColumnKey
FROM Table1 t2
WHERE t2.Key1 = t1.Key1
AND t2.Key2 = t1.Key2
ORDER BY ColumnKey
FOR XML PATH('') ),1,2,'') AS TColumnKey
FROM Table1 t1
GROUP BY t1.Key1, t1.Key2;
DECLARE @t TABLE
(
Key1 INT,
Key2 VARCHAR(10),
ColumnKey VARCHAR(32)
);
INSERT @t SELECT 1, 'idx', 'here'
UNION ALL SELECT 1, 'idx', 'there'
UNION ALL SELECT 2, 'idx', 'where'
UNION ALL SELECT 2, 'idx', 'why';
;WITH t AS
(
SELECT Key1, Key2 FROM @t -- put your real table here
WHERE Key2 = 'idx'
GROUP BY Key1, Key2
)
SELECT
TKey1 = t.Key1,
TKey2 = t.Key2,
TColumnKey = STUFF((SELECT ', ' + t2.ColumnKey
FROM @t -- put your real table here
AS t2 WHERE t2.Key1 = t.Key1
FOR XML PATH(''),TYPE).value('./text()[1]','nvarchar(max)'),1,2,'')
FROM t;
精彩评论