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
 Other SQL Server Topics (2005)
 Converting multiple rows into 1 row

Author  Topic 

pmidge
Starting Member

2 Posts

Posted - 2010-09-29 : 12:13:56
Hello,

I have a table which contains multiple email addresses and property_ids. My problem is, often the same email is duplicated but with different property_ids.

I need to output this data so that the email addresses are distinct and the property_id column shows each property_id for that user all in the same field.

So for example :

Email Property_id
a@b.com 1
a@b.com 2
a@b.com 3
a@b.com 4
a@b.com 5
c@d.com 6
c@d.com 7
c@d.com 8

Would need to become :

Email Property_id
a@b.com 1, 2, 3, 4, 5
c@d.com 6, 7, 8


I would appreciate any help at all on this.


Thanks
Paul




Ifor
Aged Yak Warrior

700 Posts

Posted - 2010-10-01 : 09:44:30
Here is the standard solution:

-- *** Test Data ***
CREATE TABLE #t
(
Property_id int NOT NULL
,Email varchar(255) NULL
)
INSERT INTO #t
SELECT 1, 'a@b.com'
UNION ALL SELECT 2, 'a@b.com'
UNION ALL SELECT 3, 'a@b.com'
UNION ALL SELECT 4, 'a@b.com'
UNION ALL SELECT 5, 'a@b.com'
UNION ALL SELECT 6, 'c@d.com'
UNION ALL SELECT 7, 'c@d.com'
UNION ALL SELECT 8, 'c@d.com'
-- *** End Test Data ***

;WITH cte
AS
(
SELECT A.Email
,STUFF(
(SELECT ' ' + CAST(B.Property_id AS varchar(20)) + ','
FROM #t B
WHERE A.EMail = B.Email
FOR XML PATH('') )
,1
,1
,'') AS Property_IDs
FROM #t A
GROUP BY A.Email
)
SELECT EMail, LEFT(Property_IDs, LEN(Property_IDs) - 1) AS Property_IDs
FROM cte

Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2010-10-01 : 10:44:49
Or a slightly more readable one (but I think the execution plan would be similar)


SELECT
em.[email] AS [Email]
, LEFT(ids.[ids], LEN(ids.[ids]) - 1) AS [Ids]
FROM
(
SELECT DISTINCT [email] FROM #t
)
AS em

CROSS APPLY (
SELECT CAST(t.[Property_ID] AS VARCHAR(10)) + ','
FROM #t AS t
WHERE t.[email] = em.[email]
FOR XML PATH('')
)
AS ids ([ids])

In fact the execution plans *are* identical for this table

Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION
Go to Top of Page
   

- Advertisement -