Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Concat column data in single row for group data

Author  Topic 

abhit_kumar
Posting Yak Master

147 Posts

Posted - 2010-03-05 : 04:17:12
Hello Experts,

I have made a query based upon that the output is come as follow:-



VendorName ItemCode InvNo Qty Price SerialNo
ABC Item1 1001 50 120 4100/01
ABC Item1 1001 50 120 4100/02
ABC Item1 1001 50 120 4100/03
ABC Item1 1001 50 120 4100/04



Output should be like this:-



VendorName ItemCode InvNo Qty Price SerialNo
ABC Item1 1001 50 120 4100/01,4100/02,4100/03,4100/04

Means we need to concat all serial no in one row itself for a sinle group of data.

Please help me.

Regards,
abhi

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-03-05 : 04:22:24
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81254

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2010-03-05 : 04:29:59
Try this

DECLARE @temp TABLE ( VendorName VARCHAR(100), ItemCode VARCHAR(100),InvNo INT, Qty INT,Price INT, SerialNo VARCHAR(100))
INSERT INTO @temp
SELECT 'ABC', 'Item1', 1001, 50, 120, '4100/01' UNION ALL
SELECT 'ABC', 'Item1', 1001, 50, 120, '4100/02' UNION ALL
SELECT 'ABC', 'Item1', 1001, 50, 120, '4100/03' UNION ALL
SELECT 'ABC', 'Item1', 1001, 50, 120, '4100/04'

SELECT DISTINCT
VendorName,
ItemCode,
InvNo,
Qty,
Price,
STUFF(( SELECT DISTINCT ','+SerialNo
FROM @temp
WHERE VendorName = T.VendorName
AND ItemCode = T.ItemCode
AND InvNo = T.InvNo
AND Qty = T.Qty
AND Price = T.Price
FOR XML PATH('')),1,1,'') AS SerialNo
FROM @Temp T
Go to Top of Page

abhit_kumar
Posting Yak Master

147 Posts

Posted - 2010-03-05 : 05:20:38
Thanks Raky and Madhivan
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2010-03-05 : 06:07:15
quote:
Originally posted by abhit_kumar

Thanks Raky and Madhivan



Welcome..
Go to Top of Page

abhit_kumar
Posting Yak Master

147 Posts

Posted - 2010-03-05 : 06:42:35
hello raky,

can u please tell me why we have used

FOR XML PATH('')),1,1,''
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2010-03-05 : 06:52:38
quote:
Originally posted by abhit_kumar

hello raky,

can u please tell me why we have used

FOR XML PATH('')),1,1,''



stuff(( select ','+Colval for xml path('')),1,1,'')

in this

we are using for xml path to make the values in colval column to get concatenate seprated by ',' and we are using stuff function to remove ',' which is appended to first value.
Go to Top of Page
   

- Advertisement -