我认为您正在寻找这样的东西:
create table BookSubjects(SubjectID int,BookID int)
insert into BookSubjects(SubjectID ,BookID ) values(1,10)
insert into BookSubjects(SubjectID ,BookID ) values(2,20)
insert into BookSubjects(SubjectID ,BookID ) values(3,30)
insert into BookSubjects(SubjectID ,BookID ) values(4,40)
insert into BookSubjects(SubjectID ,BookID ) values(5,50)
insert into BookSubjects(SubjectID ,BookID ) values(6,60)
insert into BookSubjects(SubjectID ,BookID ) values(2,10)
insert into BookSubjects(SubjectID ,BookID ) values(2,10)
insert into BookSubjects(SubjectID ,BookID ) values(3,10)
insert into BookSubjects(SubjectID ,BookID ) values(4,10)
insert into BookSubjects(SubjectID ,BookID ) values(5,10)
insert into BookSubjects(SubjectID ,BookID ) values(6,10)
select * from BookSubjects
;With Rep As
(
SELECT [SubjectID],[BookID] FROM [BookSubjects]
WHERE [BookID] = 10
)
, Rep1 As
(
select
[BookID],
stuff((
select ',' + cast(t.[SubjectID] as varchar(100))
from Rep t
where Rep.[BookID] = t.[BookID]
order by t.[SubjectID]
for xml path('')
),1,1,'') as name_csv
from Rep
group by [BookID]
)
select * from rep1
我在第二个 With(Named Rep1) 中的第一个 With 之后使用另一个 With 子句我转换行返回两个逗号分隔的列。你可以改变你的需要。