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
 Tricky query

Author  Topic 

aznan
Starting Member

3 Posts

Posted - 2008-11-03 : 10:38:13
Hi
I have these 2 tables, Foo and Bar which each have their id and name columns, and which are linked many-to-many. However, rather than having an intermediate table, Foo has eight columns of Bar_id1, Bar_id2, Bar_id3... If a Foo doesn't have 8 Bars, then the remaining columns will be null.

How do I make a query which selects every row and column of Foo, while replacing the Foo's Bar_ids with the corresponding Bar's Bar_names? In other words, I want the result displaying

Foo_id, Foo_name, Bar_name1, Bar_name2, ..., Bar_name8

I just can't figure this out.
Please help!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-03 : 10:39:45
Are you using sql 2005?
Go to Top of Page

aznan
Starting Member

3 Posts

Posted - 2008-11-03 : 10:47:49
Yes
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-03 : 10:51:10
under any case you can use below

SELECT f.id,f.name,b.Bar_name,IDENTITY(int,1,1) AS RowID
INTO #Temp
FROM (SELECT id,
name,
Bar_id1 as Bar_id
FROM Foo
UNION ALL
SELECT id,
name,
Bar_id2 as Bar_id
FROM Foo
UNION ALL
SELECT id,
name,
Bar_id3 as Bar_id
FROM Foo
UNION ALL
....
SELECT id,
name,
Bar_id8 as Bar_id
FROM Foo )f
INNER JOIN Bar b
ON b.Bar_id=f.Bar_id

SELECT id,name,
MAX(CASE WHEN Seq=1 THEN Bar_name ELSE NULL END) AS Bar_name1,
MAX(CASE WHEN Seq=2 THEN Bar_name ELSE NULL END) AS Bar_name2,
.......
MAX(CASE WHEN Seq=8 THEN Bar_name ELSE NULL END) AS Bar_name8
FROM
(
SELECT (SELECT COUNT(*) FROM #Temp WHERE id=id and name =t.name
AND RowID<=t.RowID) AS Seq,*
FROM #Temp t
)r
GROUP BY id,name

DROP TABLE #Temp
Go to Top of Page

aznan
Starting Member

3 Posts

Posted - 2008-11-03 : 10:53:37
Thanks a bunch! Will try.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-03 : 10:58:38
in sql 2005 you can use UNPIVOT also

;With CTE (Foo_id,Foo_name,Bar_id) AS
(
SELECT id,name,IDVal
FROM (SELECT * FROM Foo)t
UNPIVOT (IDVal FOR ID IN ([Bar_id1],[Bar_id2],...[Bar_Id8]))p
)

SELECT *
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY id,name ORDER BY BarId) AS Seq,*
FROM CTE c
INNER JOIN Bar b
OB b.Bar_id=c.Bar_Id
)m
PIVOT(MAX(Bar_name) FOR Seq IN ([1],[2],..))p
Go to Top of Page
   

- Advertisement -