sql 把所有行轉成一個字符串?
文章從騰訊雲問答看到的,但是原文應該在
Stack Overflow沒有找到鏈接,騰訊雲鏈接:https://cloud.tencent.com/developer/ask/57675
我知道在SQL服務器我們不能使用Group_concat函數,但這里有一個問題,我有我需要Group_Concat我的查詢。我谷歌它發現了一些邏輯,但無法糾正它。我的SQL查詢是:
select m.maskid,m.maskname,m.schoolid,s.schoolname,
md.maskdetail
from tblmask m join school s on s.id = m.schoolid
join maskdetails md on m.maskid = md.maskid
order by m.maskname ;
它給了我這樣的結果:

我想要我的輸出成這樣:

解決辦法:
添加下面這段代碼就可以的:
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, STUFF((
SELECT ',' + T.maskdetail
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH('')), 1, 1, '') as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by A.maskid
, A.maskname
, A.schoolid
, B.schoolname
