[英]Group by with Comma Separated Values and excluding the value from the previous column value
我有兩個表 Lecturer 和 Student,我想在新列中用逗號分隔值顯示另一個講師 ID。 我正在使用 SQL 服務器 2014。
Table: Lecturer
id name subject UNIVERSITYADDRESS
102 Mark Designing Michigan
103 John Analytics Michigan
104 Jacob Science Michigan
Table: StudentLecturer
id Fname Lname Lid
1 Jack P 102
1 Jack P 103
1 Jack P 104
通過使用 group by 我得到一個值,如下所示:
SELECT id,fname,lname,lid from studentlecturer g`roup by id
Table: StudentLecturer
id Fname Lname Lid
1 Jack P 102
預期結果
id Fname Lname Lid Concat Values
1 Jack P 102 103,104
1 Jack P 103 102,104
1 Jack P 104 102,103
SQL 小提琴:( http://sqlfiddle.com/#!7/28f5f/11 )
您可以使用for xml
來匯總您的值。 Stuff
刪除了最初的逗號。
select *
from StudentLecturer s
outer apply (
select ConcatValues=Stuff((select ',' + Cast(l.Id as varchar(10))
from Lecturer l where l.id != s.Lid
for xml path('')),1,1,'')
)l
這可以使用For XML Path("), TYPE
如下:
SELECT S.id, S.Fname, S.Lname, S.Lid,
STUFF((SELECT Concat(',',Lid) FROM StudentLecturer WHERE id=S.id And Lid<>S.Lid
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'') AS [Concat Values]
FROM StudentLecturer As S
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.