I’ve been studying for my MCP in database design (70-229) recently when I found this simple and useful query technique.
You have to run a report against two related tables. Let’s use the Employee and Orders tables from the Northwind sample database.
You want to see a row for every record in the Employee table; however the report has to be filtered using criterion which applies to both tables e.g.
Region = ‘WA’ (Employee table)
Order Date > ’07/12/1996′ (Orders Table)
What you want is a row for each employee record with NULLs placed in the fields that do not match the criteria.
It’s easy to apply this criterion and obtain output that returns employees that match the criteria, but not all employees would be outputted i.e. those that do not match the criteria.
Here is the SQL to obtain the desired output:
SELECT E.LastName, O.OrderID, O.OrderDate, E.Region FROM Employees E LEFT OUTER JOIN Orders O ON E.EmployeeID = O.EmployeeID AND E.Region = 'WA' AND O.OrderDate > '1996-07-12' ORDER BY E.LastName
Note that there is no WHERE clause.
Output: (SQL Server 2000)
Unfortunately this SQL doesn’t work in Access.