SQL Server 2000 - How do I rotate the results of a join in the final results of a query?
My database is quite complex so I've simplified my problem down to the tables below.
TableA
and TableB
are related by the NameID
field in TableB
. I am trying to create a SQL statement to produce the desired results. I'm understand JOINs and how they work but I can't fogure this out.
There will never be more than开发者_高级运维 2 items in TableB
for each item in TableA
. There could be less than 2 items.
This will be used on a SQL Server 2000 server.
TableA
ID | Name
---+-----
1 | John
2 | Jane
3 | Bob
4 | Doug
TableB
ID | NameID | Information
---+--------+------------
1 | 1 | Apples
2 | 1 | Apples
3 | 2 | Pears
4 | 2 | Grapes
5 | 3 | Kiwi
Desired Result
ID | Name | InformationA | InformationB
---+------+--------------+-------------
1 | John | Apples | Apples
2 | Jane | Pears | Grapes
3 | Bob | Kiwi | NULL
4 | Doug | NULL | NULL
(Edited to give the preferred ordering for the two columns)
SELECT a.Id,
a.Name,
STUFF(MIN(STR(b.Id, 10) + b.Information), 1, 10, '') AS InformationA,
CASE
WHEN COUNT(b.Id) = 2 THEN STUFF(MAX(STR(b.Id, 10) +
b.Information), 1, 10, '')
END AS InformationB
FROM TableA a
LEFT JOIN TableB b
ON a.Id = b.NameId
GROUP BY a.Id,
a.Name
I think what you need to do is a pivot. Take a look and see if that suits your needs.
精彩评论