3

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Justin808
  • 20,859
  • 46
  • 160
  • 265

2 Answers2

3

(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  
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
-1

I think what you need to do is a pivot. Take a look and see if that suits your needs.

Chris B. Behrens
  • 6,255
  • 8
  • 45
  • 71
  • I don't think PIVOT is available in SQL Server 2000. – bobs Jan 12 '11 at 18:39
  • This was introduced in SQL2005. (originally had 2008, whoops) – Justin808 Jan 12 '11 at 18:40
  • Ah, sorry. Here's a StackOverflow question with a reference to that problem, though: http://stackoverflow.com/questions/312861/pivot-using-sql-server-2000. That question in turn references this: http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables. – Chris B. Behrens Jan 12 '11 at 18:43