2

我有一个包含值的表:

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
4

2 回答 2

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;
于 2011-07-08T21:35:34.930 回答
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('./text()[1]','nvarchar(max)'),1,2,'')
    FROM t;
于 2011-07-08T21:47:44.267 回答