x

Retrieve columns from multiple tables

I have a requirement that i have two tables 1.customer(cust_id(PK),addr_id,email) 2.customer_order(order_id,cust_id(FK))

My requirement is to get email and order_ids(order_ids in comma seperated value for each cust_id)

more ▼

asked Nov 24, 2011 at 04:18 AM in Default

avatar image

sumanbanda
0 1 1 2

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

I believe you want to do something like this

 DECLARE @customer TABLE 
 (cust_id INT PRIMARY KEY,
 email VARCHAR(50)
 ) 
 DECLARE @customer_order TABLE (order_id INT PRIMARY KEY,cust_id INT)
 
 -- TEMPORARY DATA INSERTION
 
 INSERT @customer
         (
          [cust_id]
         ,[email]
         )
 SELECT 1, 'a@mail.com'
 UNION ALL
 SELECT 2, 'b@mail.com'
 
 INSERT @customer_order
         (
          [order_id]
         ,[cust_id]
         )
 SELECT 1, 1
 UNION ALL
 SELECT 2, 1
 UNION ALL
 SELECT 3,1
 UNION ALL
 SELECT 4,2
 UNION ALL
 SELECT 5,2
 
 
 -- FINAL OUTPUT
 SELECT  [cust_id]
 ,       email
 ,       STUFF(( SELECT  ',' + CAST([order_id] AS VARCHAR(50))
                 FROM    @customer_order AS CO
                 WHERE   CO.[cust_id] = C.[cust_id]
               FOR
                 XML PATH('')
               ), 1, 1, '')
 FROM    @customer AS C
more ▼

answered Nov 24, 2011 at 04:40 AM

avatar image

Usman Butt
13.9k 6 12 21

thanks for the answer which i am looking for exactly.....

Nov 24, 2011 at 05:27 AM sumanbanda
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x2016

asked: Nov 24, 2011 at 04:18 AM

Seen: 641 times

Last Updated: Nov 24, 2011 at 04:18 AM

Copyright 2016 Redgate Software. Privacy Policy