Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hey guys, I have 2 tables:Attributes AtrributeVales attrId(PK) name id (PK) attrId(FK) value1 color 1 1 green2 size 2 2 small 3 1 red 4 2 medium 5 1 blue 6 2 largeI need to build some query that will return something like this:Color SizeGreen smallRed mediumBlue largeAny ideas of how accomplish this task??? Any kind of help would be appreciated...
webfred
Master Smack Fu Yak Hacker
8781 Posts
Posted - 2011-01-14 : 01:13:10
quote:Originally posted by _michael_ Hey guys, I have 2 tables:
Attributes AtrributeVales attrId(PK) name id (PK) attrId(FK) value1 color 1 1 green2 size 2 2 small 3 1 red 4 2 medium 5 1 blue 6 2 largeI need to build some query that will return something like this:Color SizeGreen smallRed mediumBlue large
Any ideas of how accomplish this task??? Any kind of help would be appreciated...
More readable...No, you're never too old to Yak'n'Roll if you're too young to die.
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2011-01-14 : 02:45:16
Thanks webfred for the formatting. It helps assuming that the color/size are always in pair and the id is consecutive and you are using SQL 2005 / 2008
select [color], [size]from ( select row = (av.id-1)/2, av.value, a.name from AttributeValues av inner join Attributes a on av.attrId = a.attrId ) d pivot ( max(value) for name in ([color], [size]) ) p