我認爲你正在尋找的財產以後這樣 :
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