30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11: <strong>SQL</strong> Refactoring<br />

For a certain year, we need to report:<br />

• the average and maximum monthly sales order values, per territory, per salesperson<br />

• the average monthly sales order value, and numbers sold, per product, per territory.<br />

Clearly, these requirements produce two result sets. In each case, the approach is<br />

the same.<br />

1. Shrink the scope of the problem, mentally, to a single territory and sales person.<br />

2. Break up the request into steps that are easy to solve.<br />

3. Create a solution for each step and use that solution in the next step.<br />

This approach is demonstrated in the reporting query in Listing 11-1, which calculates the<br />

average and maximum monthly sales order values, per territory, per salesperson.<br />

DECLARE @year INT<br />

SELECT @year = 2004<br />

- – Helper date range for efficient query<br />

DECLARE @dateFrom DATETIME ,<br />

@dateTo DATETIME<br />

SELECT<br />

@dateFrom = DATEADD(yyyy, @year – 1900, '19000101') ,<br />

@dateTo = DATEADD(yyyy, 1, @dateFrom)<br />

/*<br />

average sales per territory per person per month<br />

for a given year<br />

*/<br />

/*<br />

Step 1:<br />

query the Sales.SalesTerritory table<br />

for the given year<br />

Step 2:<br />

join to the Sales.SalesOrderHeader to<br />

get SalesPersonID, and other data, in date range<br />

Steps 3-5:<br />

we need SalesPerson Name and Title by joining<br />

314

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!