Sql 分组见解 Xml

Sql Grouping insight Xml

我需要根据 id 将不同的行数据获取到 1 行,并且需要按其状态分组。

我尝试了几种方法,最终找到了使用 xml 的解决方案,但是当我使用 xml 时,我没有得到我想要的输出。

这是我用来尝试逻辑的示例代码。

drop table  #TestTable
-- Create table
CREATE TABLE #TestTable (id VARCHAR(100), title VARCHAR(100), 
progress VARCHAR(100))
GO
-- Populate tableid
INSERT INTO #TestTable (id, title, progress)
SELECT '1', 'test1', 'inprogress'
UNION ALL
SELECT '1', 'test2', 'inprogress'
UNION ALL
SELECT '1', 'test3', 'completed'
UNION ALL
SELECT '1', 'test4', 'completed'

GO

SELECT id,progress, comments = STUFF((SELECT +' , '+ TITLE
    FROM #TestTable AS x2 WHERE ID = x.ID 
   
     ORDER BY ID
     FOR XML PATH(''), TYPE).value(N'(./text())[1]', N'varchar(max)'), 1, 1, '')
FROM #TestTable AS x 


GROUP BY id,progress 

返回的输出:

id  progress      comments
1   completed   , test1 , test2 , test3 , test4
1   inprogress  , test1 , test2 , test3 , test4

预期输出:

id  progress     comments
1   completed   , test1 , test2 
1   inprogress  , test3 , test4

我认为您在加入 (progress = x.progress) 中缺少一个条件:

SELECT id,progress, comments = STUFF((SELECT +' , '+ TITLE
    FROM #TestTable AS x2 WHERE ID = x.ID  
        and progress = x.progress  -- <-- add this 
        ORDER BY ID
     FOR XML PATH(''), TYPE).value(N'(./text())[1]', N'varchar(max)'), 1, 1, '')
FROM #TestTable AS x 
GROUP BY id,progress 

输出: