返回连接的num和ordersource的最大数量

时间:2012-12-14 07:53:18

标签: sql-server sql-server-2008 tsql

create table test(id int ,num numeric(10),[Ordersource] varchar(10)) 
insert into test (id,num,[Order])values(1,10,'s1'),(1,10,'s2'),(1,10,'s3'),(1,10,'s4'),(1,12,'s5'),(1,12,'s6'),(2,13,'s6')

我想输出格式是

id num ordersource
1 10   s1,s2,s3,s4 

2 个答案:

答案 0 :(得分:4)

希望这会有所帮助

Declare @test table (id int ,num numeric(10),[Order] varchar(10)) 
Insert into @test (id,num,[Order])
Values(1,10,'s1'),(1,10,'s2'),(1,10,'s3'),(1,10,'s4'),(1,12,'s5'),(1,12,'s6'),(2,13,'s6')

;With Cte As
(
    Select 
        X.* 
        ,rn=Dense_Rank()over(order by cnt desc)
    From (
    Select  
        id
        , num
        ,ordersource = Stuff((
            Select ',' + Cast([Order] As Varchar(Max))
            From @test t2 
            Where t1.id = t2.id and t1.num = t2.num
            For Xml Path('')
         ),1,1,'')
        ,cnt = count(num) over(partition by id, num)        
    From @test t1)X
)
Select distinct id, num,ordersource
From Cte
Where rn = 1

enter image description here

答案 1 :(得分:1)

另一种方法:

select id, num, left(s, len(s) - 1)
from (
    select distinct t2.id, t2.num, (
        select t1.O + ', ' as 'text()'
        from test t1
        where t1.id = t2.id and t1.num = t2.num
        order by t1.id, t1.num
        for xml path('')) s
    from test t2) temp
where
    id = 1
    and num = 10