没有sql中的while循环怎么做呢

时间:2015-06-04 08:31:49

标签: sql sql-server

我有一张这样的表,

import same.library

我需要输出,

A         |        B
----------------------
1         |       10
1         |       20
2         |       30
2         |       40

提前谢谢

1 个答案:

答案 0 :(得分:3)

试试这个。

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