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)
 Vertical to horizontal record

Author  Topic 

martalex
Starting Member

17 Posts

Posted - 2009-07-14 : 17:22:11
I have the following table.

Group Type QTY Reason
-------------------------------
1 Type1 20 Reason1
1 Type2 10 Reason2
2 Type1 25 Reason1
2 Type2 0 Null


I need to return the data in the following format.

Group, Type1_Qty, Type1_Reason, Type2_Qty, Type2_Reason
---------------------------------------------------------------------
1 20 Reason1 10 Reason2
2 25 Reason1 0 Null

Any suggestion?

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-07-14 : 17:48:03
PIVOT.




N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

martalex
Starting Member

17 Posts

Posted - 2009-07-14 : 20:47:14
Ok, but i'm confused how to deal with Reason. How can I aggregate a varchar?
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-07-15 : 00:27:07
try any one these

select groupid,max(type1qty)as type1_qty,max(type1reason)as type1_reason,max(type2qty)as type2_qty,max(type2reason)as type2_reason
from (
select groupid,([type1]) as type1qty,([type2]) as type2qty,null as type1reason,null as type2reason
from @tab
pivot (max(qty) for type in ([type1],[type2]))p
union
select groupid,null,null,([type1]),([type2])
from @tab
pivot (max(reason) for type in ([type1],[type2]))p
)s
group by groupid

select groupid,
max(case when type = 'type1' then qty end) as 'type1_qty',
max(case when type = 'type1' then reason end) as 'type1_reason',
max(case when type = 'type2' then qty end) as 'type2_qty',
max(case when type = 'type2' then reason end) as 'type2_reason'
from tablename
group by groupid
Go to Top of Page
   

- Advertisement -