选择“循环时间”并使用值集合

时间:2013-12-02 13:47:35

标签: sql-server

(抱歉我的英语很差!)

我有一个包含几个字段的表

PK      Name1    Name2       Value    
1       nmAA     nm2AAA      01A
2       nmAA     nm2AAA      01B
3       nmAA     nm2AAA      01c

我需要有这个结果

Name1    Name2       ValueList
nmAA     nm2AAA      01A, 01B, 01c

我正在考虑在循环中放入一个变量(ValueList)Value字段的结果。我不知道如何在SQL SERVER中执行此操作。

2 个答案:

答案 0 :(得分:0)

您可以使用FOR XML功能执行此操作:

SELECT 
  t1.Name1,
  t1.name2,
  STUFF((
    SELECT ', ' + t2.Value
    FROM Table1 t2
    WHERE t2.Name1 = t1.Name1
      AND t2.Name2 = t1.Name2
    FOR XML PATH (''))
  ,1,2,'') AS [Values]
FROM Table1 t1
GROUP BY t1.Name1, 
         t1.Name2;

答案 1 :(得分:0)

DECLARE @t TABLE (PK INT,Name1 VARCHAR(20),Name2 VARCHAR(20),Value VARCHAR(20))
INSERT INTO @t
VALUES    
(1,'nmAA','nm2AAA','01A'),
(2,'nmAA','nm2AAA','01B'),
(3,'nmAA','nm2AAA','01c')


SELECT DISTINCT Name1, Name2, STUFF(ValueList, 1 ,2 , '') AS ValueList
FROM @t t 
        CROSS APPLY (
                     SELECT ', '+ Value [text()]
                     FROM @t
                     WHERE Name1 = t.Name1 
                     AND   Name2 = t.Name2
                     FOR XML PATH('')
                    )Q(ValueList)

结果集

Name1   Name2   ValueList
nmAA    nm2AAA  01A, 01B, 01c