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 2008 Forums
 Transact-SQL (2008)
 Splitting out results from duplicate data

Author  Topic 

baconsolo
Starting Member

3 Posts

Posted - 2011-12-07 : 08:53:50
Hi,

I have a table that contains an identifier and some name/address details some of the records have the same ID number but different details E.G.

ID Name Address
1 Billy 10 Oak terrace
1 Johnny 12 Oak terrace

How can I copy this data to another table so it looks like this. It becomes a single, rather than double line entry.

ID Name1 Name2 Address1 Address2
1 Billy Johnny 10 Oak terrace 12 Oak terrace

Many Thanks

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-07 : 08:59:00
will it be always 2 records per id? what happens if there are more? you want all of them to be returned as separate fields?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

baconsolo
Starting Member

3 Posts

Posted - 2011-12-07 : 09:06:40
It would be no more than 2 duplicated numbers.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-07 : 09:09:40
[code]
SELECT ID,
MAX(CASE WHEN Rn=1 THEN Name END) AS Name1,
MAX(CASE WHEN Rn=2 THEN Name END) AS Name2,
MAX(CASE WHEN Rn=1 THEN Address END) AS Address1,
MAX(CASE WHEN Rn=2 THEN Address END) AS Address2
FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name ASC) AS Rn,*
FROM Table
)t
GROUP BY ID
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

baconsolo
Starting Member

3 Posts

Posted - 2011-12-07 : 11:13:27
thank you for the reply.

does the select statement at the top need to be joined to the select statement in brackets in someway?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-07 : 11:18:22
the select inside is a derived table

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -