我有一个包含值的表:
Key1 Key2 ColumnKey
1 idx here
1 idx there
2 idx where
2 idx why
我需要返回,因为 Key1,Key2 都相同,columnKey 用逗号分隔。
示例:代替
1 idx here
1 idx there
需要退货
1 idx here, there
有效的查询:
DECLARE @commaSeperatedRes NVARCHAR(MAX);
SELECT @commaSeperatedRes = COALESCE(@commaSeperatedRes + ', ', '') + ColumnKey
FROM Table1
WHERE Table1.Key1= 1 AND Table1.Key2 = 'idx';
print @commaSeperatedRes
问题是,我需要返回不止一行:
1 idx here, there
2 idx where, why
DECLARE @commaSeperated NVARCHAR(MAX);
SELECT @commaSeperatedRes = COALESCE(@commaSeperated + ', ', '') + ColumnKey
FROM Table1
WHERE (Table1.Key1= 1 and Table1.Key2 = 'idx')
OR
( Table1.Key1 = 2 Table1.Key2 = 'idx')
print @commaSeperatedRes
此外,我会将这些结果插入到一个临时表中,以便将这些值与其他表中的更多列合并。理想情况下,我将使用的临时表应如下所示:
TKey1 TKey2 TColumnKey
1 idx here, there
2 idx where, why