是的,这是可能的。我包括你可以复制/粘贴到您的查询窗口为例,使用这个例子建立你的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的概念。 –