Solved

SQL Summarise entires into one line

Posted on 2014-12-15
3
63 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
  • 2
3 Comments
 
LVL 33

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
xpath sql query 2008 8 42
SQL Statement to Update Email Domain 2 21
TSQL previous 5 23
Help with Sorting Full Text results 2 14
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

911 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now