sql分组洞察xml

zsbz8rwp  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(296)

我需要得到不同的行数据,以1行为基础的id和需要按其状态分组。
我尝试了几种方法,最终找到了一个使用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
3ks5zfa0

3ks5zfa01#

我认为你的加入缺少一个条件( 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

输出:

相关问题