我认为你正在寻找的财产以后这样 :
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
我在第二个用另一种随着第一条后的带(命名REP1) 我转换行返回两个逗号塞佩额定colomn。 你可以改变你的需要。
原代码删除条目... – Lucero 2012-07-09 01:14:07