是的,這是可能的。我包括你可以複製/粘貼到您的查詢窗口爲例,使用這個例子建立你的SQL返回所需的數據:
declare @tbl table(ID int, AnotherID int)
declare @aa varchar (200)
declare @result table(ID int, AnotherIDs varchar(200))
set @aa = ''
insert into @tbl (ID, AnotherID) Values(1,1)
insert into @tbl (ID, AnotherID) Values(1,2)
insert into @tbl (ID, AnotherID)Values(1,3)
insert into @tbl (ID, AnotherID) Values(1,4)
insert into @tbl (ID, AnotherID) Values(2,1)
insert into @tbl (ID, AnotherID) Values(2,2)
insert into @tbl (ID, AnotherID) Values(2,3)
insert into @tbl (ID, AnotherID) Values(2,4)
--select * from @tbl
declare @i int
select @i = min(ID) from @tbl
declare @max int
select @max = max(ID) from @tbl
while @i <= @max begin
select @aa =
coalesce (case when @aa = ''
then CAST(AnotherID as varchar)
else @aa + ',' + CAST(AnotherID as varchar)
end
,'')
from @tbl where [email protected]
insert into @result(ID, AnotherIDs)
values(@i, @aa)
set @aa=''
set @i = @i + 1
end
select * from @result
結果是這樣的:
IDAnotherIDs
1 1,2,3,4
2 1,2,3,4
是的。使用一個PIVOT – Dbloch
必須知道你的數據庫結構來回答這個問題。包括你的模式。 –
它可以更容易地使用ORM實體框架或返回數據表並在代碼中解析它。任何T-SQL解決方案都會強制你在代碼上做一些工作,因爲在sql中沒有List的概念。 –