May 27, 2010 at 1:33 pm
I have to tables for a report. the first table has customers and the second table has orders for customers. I would like to create a query and/or report in SSRS to show each customer and all orders for that customer in one row rather than displaying the customer info for every order.
eg.
Instead of this
IDNAMEOrders
1HarryOrder1
1HarryOrder2
I want this
IDNAMEOrders
1HarryOrder1, Order2
Any assiatance is appreciated:-)
May 27, 2010 at 1:56 pm
cmckenzie-656927 (5/27/2010)
I have to tables for a report. the first table has customers and the second table has orders for customers. I would like to create a query and/or report in SSRS to show each customer and all orders for that customer in one row rather than displaying the customer info for every order.eg.
Instead of this
IDNAMEOrders
1HarryOrder1
1HarryOrder2
I want this
IDNAMEOrders
1HarryOrder1, Order2
Any assiatance is appreciated:-)
SELECT ID,
Name,
Order1= max(case WHEN Orders='Order1' then Orders else NULL end),
Order2= max(case WHEN Orders='Order2' then Orders else NULL end)
FROM <YourTable>
GROUP BY ID, Name
If you need more help:
1. see the first link in my signature, then post back here with the information requested there, as well as expected output based upon the sample data provided.
2. See the links in my signature on CROSS TABS/PIVOT.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
May 27, 2010 at 2:07 pm
If you want to get your results in one column rather than pivoted you could use the FOR XML "trick":
SELECT
ID, NAME,
STUFF((SELECT ', ' + Orders FROM YourTable t2 WHERE t2.ID = t1.ID FOR XML PATH('')),1,2,'') as Orders
FROM
YourTable t1
GROUP BY
ID, NAME
May 27, 2010 at 2:28 pm
Good going Lutz. I completely missed that he specified one column with CSV output... Thanks!
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
May 27, 2010 at 2:33 pm
Thanks lutz. It works but I don't know what you did with the for XML trick so I need to read up on that.
May 27, 2010 at 3:22 pm
The following two threads might help you to understand the usage of FOR XML as well as STUFF:
http://www.sqlservercentral.com/Forums/FindPost679589.aspx
and
http://www.sqlservercentral.com/Forums/FindPost873866.aspx
The former has some sample code that should help you understand the concept and the latter goes a step further and describe how to deal with "embedded characters such as '&', '<', '>' (and so on)" (to quote a portion Paul's post).
Viewing 6 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply