以逗号分隔的列返回列,用于键上的多个条件或多个行

时间:2011-07-08 21:15:26

标签: sql-server-2008 coalesce csv

我有一张价值表:

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

2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分:0)

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('.','nvarchar(max)'),1,2,'')
    FROM t;