simple SQL for reporting

I’ve been studying for my MCP in database design (70-229) recently when I found this simple and useful query technique.

Scenario:
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)

Output from SQL code

Output from SQL code

Unfortunately this SQL doesn’t work in Access.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s