SQL 服务器:如何合并行

SQL Server: How to combine rows

我有一个查询

select top 10 Col1,Col2,Col3 from tab1

这给了我

(1, 1, 1)
(5, 2, 59)
(8, 3, 69)
(9, 4, 70)
(10, 5, 71)
(11, 6, 72)
(11, 7, 73)
(11, 8, 74)
(11, 9, 75)
(11, 10, 76)

我想将结果压缩为

    (1, 1, 1)
    (5, 2, 59)
    (8, 3, 69)
    (9, 4, 70)
    (10, 5, 71)
    (11, 6, 72,73,74,75,76)

我如何在 select 查询中做到这一点?

编辑

注意所有列都是int类型。在查询结果中,我不介意第三列是否转换为 varchar

编辑

最终,我将查询结果存储在数据框中。使用数据框会更容易实现吗?

您可以使用以下技巧来完成此操作。请注意,我以可使用的格式发布了 ddl 和示例数据。以后你自己做吧。

if OBJECT_ID('tempdb..#something') is not null
    drop table #something

create table #something
(
    Col1 int
    , Col2 int
    , Col3 int
)

insert #something
select * 
from (Values
(1, 1, 1),
(5, 2, 59),
(8, 3, 69),
(9, 4, 70),
(10, 5, 71),
(11, 6, 72),
(11, 7, 73),
(11, 8, 74),
(11, 9, 75),
(11, 10, 76))x(Col1, col2,col3)

select Col1
    , MIN(Col2) as Col2
    , Stuff((select ',' + cast(Col3 as varchar(4))
        from #something s2
        where s2.Col1 = s.Col1
        for xml path('')), 1,1 , '') as Col3
from #something s
group by Col1