使用FOR XML合併多行查詢數據到一行

--新建ClassInfo

create table ClassInfo

(

    CID  int identity(1,1), --本表ID

    CNumber int,            --班級人數

    CName varchar(10)       --班級名稱

);

--給表ClassInfo新增測試數據

insert ClassInfo

       select 20,'一年級班'

union  select 20,'一年級班'

union  select 20,'一年級班'

union  select 20,'一年級班';

 

--新增表Students(CID 班級表外鍵,SID學生信息表ID學生的學號就是,SName)

create table Students

(

    [SID] int identity(1,1), --學號

    CID int,                 --班級ID 

    SName varchar(10)         --姓名      

);

 

--Students新增測試數據

insert into Students

      select 1,''

union select 1,''

union select 1,''

union select 1,''

union select 2,''

union select 2,'';

 

按班級顯示人員信息

SELECT a.CID,

       STUFF((SELECT ','+SName

               FROM Students AS b

               WHERE b.CID = a.CID

               FOR XML PATH('')),1,1,'') AS SName

FROM Students AS a   

GROUP BY a.CID

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章