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)
 grouping

Author  Topic 

sconard
Starting Member

18 Posts

Posted - 2008-07-23 : 11:23:41
I would like to write a query to regroup data from a table.
Data looks like this:


Thank You

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-07-23 : 11:28:29
will you certain about number of records per id2 values? will it be having maximum of 2 records per id2?
Go to Top of Page

sconard
Starting Member

18 Posts

Posted - 2008-07-23 : 11:34:58
There may be three or four on some occasions but I will limit to two
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-07-23 : 11:40:09
quote:
Originally posted by sconard

There may be three or four on some occasions but I will limit to two


ok use this

SELECT t.id2,
MAX(CASE WHEN t.RowNo=1 THEN t.value1 ELSE NULL END) AS valueA,
MAX(CASE WHEN t.RowNo=1 THEN t.value2 ELSE NULL END) AS valueB,
MAX(CASE WHEN t.RowNo=2 THEN t.value1 ELSE NULL END) AS valueC,
MAX(CASE WHEN t.RowNo=2 THEN t.value2 ELSE NULL END) AS valueD
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY id2 ORDER BY id1) AS RowNo,
id1,id2,value1,value2
FROM YourTable
)t
GROUP BY t.id2
Go to Top of Page

sconard
Starting Member

18 Posts

Posted - 2008-07-24 : 07:52:41
I am humbled. I did not use the above method but your reply was the spark to my subquery solution.
Thanks for your assistance.
Go to Top of Page
   

- Advertisement -