Solved

SQL Summarise entires into one line

Posted on 2014-12-15
3
74 Views
Last Modified: 2014-12-15
Hi All,

I have a table with ID and Invoice_Number. Multiple invoices per ID. I want to group by ID and have Invoice_Numbers as a comma seperated line against the ID.

So

1    101
1    102
1    103
2    201
2    202

becomes

1    101, 102, 103
2    201, 202

Can someone point me in the rough direction?

Thanks
0
Comment
Question by:James Elliott
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 34

Accepted Solution

by:
ste5an earned 500 total points
ID: 40499882
Use FOR XML PATH(). E.g.

DECLARE @Sample TABLE ( ID INT, Payload INT )
 
INSERT  INTO @Sample
VALUES  ( 1, 101 ),
        ( 1, 102 ),
        ( 1, 103 ),
        ( 2, 201 ),
        ( 2, 202 );


SELECT  O.ID ,
        STUFF(( SELECT  ', ' + CAST(I.Payload AS VARCHAR(255))
                FROM    @Sample I
                WHERE   I.ID = O.ID 
				FOR XML PATH('')
              ), 1, 2, '')
FROM    @Sample O
GROUP BY O.ID;

Open in new window

0
 
LVL 12

Author Comment

by:James Elliott
ID: 40499907
Great, nearly there.

It is however cutting off the very first digit of the concatenated column.

So instead I'm getting:

1   abc
1   123
2   123
2   abc


1   bc, 123
2   23, abc
0
 
LVL 12

Author Comment

by:James Elliott
ID: 40499909
Ignore, fixed.

Thanks for your help.
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how the fundamental information of how to create a table.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question