Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

sql - Concatenate grouped rows

I would like to know is it possible from this table

ID   Price    ServiceID
1    50       11
1    -10      12
2    100      11
2    20       11

to group by ID, sum the price and concatenate serviceID, something like this:

ID   Price    ServiceID
1    40       11,12
2    120      11

It is rather simple to group by ID and sum the price, but concatenate service IDs what is troubling me.

Thank you for participating.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use:

select t.id, sum(t.price)
    , stuff((
        select distinct ',' + cast(t2.ServiceID as varchar(max))
        from @t t2
        where t2.id = t.id
        for xml path('')
    ), 1, 1, '')
from @t t
group by t.id

Output:

----------- --------------------- ---------------------
1           40,00                 11,12
2           120,00                11

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...