Assuming I have three tables : TableA (key, value) TableB (key, value) TableC (key, value)
and I want to return a value for all keys. If the key exists in TableC return that value else if the key exists in B return that value else return the value from table A
The best I have come up with so far is
SELECT key,Value FROM TableA WHERE key NOT IN (SELECT key FROM TableB) AND key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableB WHERE key NOT IN (SELECT key FROM TableC) UNION SELECT key,Value FROM TableC
But this seems pretty brute force. Anyone know a better way?
Edit: Here is a more concrete example. Consider TableA as a standard work schedule where the key is a date and the value is the assigned shift. Table B is a statutory holiday calendar that overrides the standard work week. Table C is an exception schedule that is used to override the other two schedules when someone is asked to come in and work either an extra shift or a different shift.
OK, using your concrete example as a basis, I came up with a solution different from the others posted (although I think I like your solution better). This was tested on MS SQL Server 2005 – changes may be needed for your SQL dialect.
First, some DDL to set the stage:
Using these tables/rows as a basis, this SELECT statement retrieves the desired data: