如何在sql中不使用while循环
我有一张这样的桌子如何在sql中不使用while循环,sql,sql-server,Sql,Sql Server,我有一张这样的桌子 A | B ---------------------- 1 | 10 1 | 20 2 | 30 2 | 40 我需要输出为 A | B ------------------------ 1 | 10,20 2 | 30,40 提前谢谢你试
A | B
----------------------
1 | 10
1 | 20
2 | 30
2 | 40
我需要输出为
A | B
------------------------
1 | 10,20
2 | 30,40
提前谢谢你试试这个
create table #table2(
col1 int,
col2 varchar(10),
)
insert into #table2
select 1, '10' union all
select 1, '20' union all
select 1, '30' union all
select 2, '40' union all
select 2, '50' union all
select 2, '60'
select
col1,
col2 =
stuff((
select
', ' + t2.col2
from #table2 t2
where
t2.col1 = t1.col1
for xml path(''), type).value('.', 'varchar(max)'
), 1, 2, '')
from #table2 t1
GROUP BY t1.col1
分组,可能是材料或分组或类似的。B列的哪种数据类型?它的int数据类型在本例中,您不需要在内部查询中使用group by。你确实需要一份订单by@ughai很抱歉我错了。我不能像那样插入另一张桌子,因为它的桌子太多了rows@Giri普拉萨德:我不明白,简单解释一下。@Kumar我不能像你在回答中那样提到所有的行,因为我的桌子上有很多行