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
 General SQL Server Forums
 New to SQL Server Programming
 join 2tables in specific way.

Author  Topic 

_michael_
Starting Member

1 Post

Posted - 2011-01-13 : 18:16:21
Hey guys, I have 2 tables:
Attributes AtrributeVales
attrId(PK) name id (PK) attrId(FK) value
1 color 1 1 green
2 size 2 2 small
3 1 red
4 2 medium
5 1 blue
6 2 large

I need to build some query that will return something like this:
Color Size
Green small
Red medium
Blue large

Any 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) value
1 color 1 1 green
2 size 2 2 small
3 1 red
4 2 medium
5 1 blue
6 2 large

I need to build some query that will return something like this:
Color Size
Green small
Red medium
Blue 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.
Go to Top of Page

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



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -