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.
| Author |
Topic |
|
tlbaxter
Starting Member
2 Posts |
Posted - 2009-12-22 : 16:37:51
|
| Hello,I'm using SQL Server 2008.I have a table of parts (call it "Parts"). This table has, among other things, an "Id" column. I have two other tables (call them "A" and "B") that contain foreign keys into Parts. Not every row in "Parts" has a corresponding row in tables "A" or "B". The Id columns in "A" and "B" are disjoint (i.e., they do not overlap).Here's some sample data (I only show the Id column):Parts=====232425262728A=24B=2628What I'd like is a query that returns every row in "Parts" as well as a column that contains either "A" (if there is a corresponding row in "A"), "B" (if there is a corresponding row in "B"), or null (if there is no corresponding row in "A" or "B".Here is the sample output I'm looking for:---------------23 null24 A25 null26 B27 null28 BHow can I write such a query?Thanks--Tom Baxter |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-12-22 : 16:41:43
|
SELECT p.ID, CASE WHEN a.ID IS NOT NULL THEN 'A' WHEN b.ID IS NOT NULL THEN 'B' ELSE NULL END AS Col2FROM Parts AS pLEFT JOIN TableA AS a ON a.ID = p.IDLEFT JOIN TableB AS b ON b.ID = p.ID N 56°04'39.26"E 12°55'05.63" |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-12-22 : 16:43:02
|
SELECT p.ID, x.TableNameFROM Parts AS pLEFT JOIN (SELECT 'A' AS TableName, ID FROM TableA UNION ALL SELECT 'B', ID FROM TableB) AS x ON x.ID = p.ID N 56°04'39.26"E 12°55'05.63" |
 |
|
|
tlbaxter
Starting Member
2 Posts |
Posted - 2009-12-22 : 16:58:31
|
quote: Originally posted by Peso SELECT p.ID, CASE WHEN a.ID IS NOT NULL THEN 'A' WHEN b.ID IS NOT NULL THEN 'B' ELSE NULL END AS Col2FROM Parts AS pLEFT JOIN TableA AS a ON a.ID = p.IDLEFT JOIN TableB AS b ON b.ID = p.ID N 56°04'39.26"E 12°55'05.63"
That's perfect!! It worked like a charm. Thank you so much!!!--Tom Baxter |
 |
|
|
|
|
|