📚 Chapter 13 – Creating Reports with SQL Queries
1️⃣ Fundamentals of Relational Reporting Queries
Once a dimensional data warehouse is structured and populated via ETL, business analysts and reporting tools extract business intelligence directly through relational SQL queries, views, and stored procedures.
The Reporting Lifecycle
- Identify Business Intent: Define the grain, analytical metrics, and dimensional slices requested by stakeholders.
- Script Documentation Standard: Every production SQL query must begin with a standardized script documentation header:
-- ============================================= Title: SalesByTitlesByDates Description: Analyzes title sales quantities partitioned by order date and publisher. Developer: Your Name Date: 2026-11-10 Change Log: Who, When, What -- =============================================
-
Fully Qualified Naming Syntax: Best practice requires three-part naming (Database.Schema.TableOrView). This practice prevents implicit object resolution overhead in the SQL Server query engine and facilitates code maintenance across multi-database warehouse environments.
-
Stacked Query Iteration: Stacking previous query versions in the SQL Server Management Studio (SSMS) query editor window provides an audit trail and an immediate fallback during step-by-step query construction.
2️⃣ Query Architecture & Progressive Enrichment
The Base Grain
Reporting queries originate at the fact table grain, linking outwards to surrounding dimensions:
SELECT
OrderNumber
, OrderDateKey
, TitleKey
, StoreKey
, SalesQuantity
FROM DWPubsSales.dbo.FactSales;
Star Schema Navigation with Explicit Joins
Raw integer surrogate keys (TitleKey, OrderDateKey) must be resolved into descriptive, human-readable attributes by joining dimensional tables using explicit INNER JOIN clauses and table aliases via the AS keyword:
SELECT
DP.PublisherName
, [Title] = DT.TitleName
, DT.TitleId
, [OrderDate] = CONVERT(varchar(50), DD.[Date], 101)
, FS.SalesQuantity
FROM DWPubsSales.dbo.FactSales AS FS
INNER JOIN DWPubsSales.dbo.DimTitles AS DT
ON FS.TitleKey = DT.TitleKey
INNER JOIN DWPubsSales.dbo.DimDates AS DD
ON FS.OrderDateKey = DD.DateKey
INNER JOIN DWPubsSales.dbo.DimPublishers AS DP
ON DT.PublisherKey = DP.PublisherKey
ORDER BY DP.PublisherName, [Title], DD.[Date];
Presentation & Formatting
-
Date Conversion: Relational dates stored in DimDates.[Date] are formatted for client presentation using CONVERT(varchar(50), [Date], 101) (US Standard: MM/DD/YYYY) or style 110 (MM-DD-YYYY).
-
Column Aliasing: Assign user-facing headers using bracketed alias syntax ([Title] = DT.TitleName).
3️⃣ Filtering & Dynamic Parameterization
Reports require selective filtering to avoid saturating network I/O and client memory:
| SQL Filter Pattern | Syntax Example | Functional Use Case |
|---|---|---|
| Discrete Equality | WHERE DT.TitleId = 'PS2091' |
Direct drill-down to a single dimensional entity. |
| Wildcard Pattern | WHERE DT.TitleId LIKE 'PS%' |
Prefix matching using % (zero or more characters) or _ (single character). |
| Inclusion Set | WHERE DD.[Date] IN ('09/13/1994', '05/29/1993') |
Finite multi-select dimensional filtering. |
| Range Inclusion | WHERE DD.[Date] BETWEEN '09/13/1994' AND '09/14/1994' |
Time-series bounded filtering (endpoints are inclusive). |
Dynamic Filtering with Variables & Parameter Flags
To support reporting interfaces (such as SSRS or Power BI parameters), queries declare variables and conditional boolean bypass flags (@ShowAll):
DECLARE
@ShowAll nvarchar(4) = 'False'
, @StartDate datetime = '1994-09-13'
, @EndDate datetime = '1994-09-14'
, @Prefix nvarchar(3) = 'PS%';
SELECT
DP.PublisherName
, [Title] = DT.TitleName
, DT.TitleId
, [OrderDate] = CONVERT(varchar(50), DD.[Date], 101)
, [Total for that Date by Title] = SUM(FS.SalesQuantity)
FROM DWPubsSales.dbo.FactSales AS FS
INNER JOIN DWPubsSales.dbo.DimTitles AS DT
ON FS.TitleKey = DT.TitleKey
INNER JOIN DWPubsSales.dbo.DimDates AS DD
ON FS.OrderDateKey = DD.DateKey
INNER JOIN DWPubsSales.dbo.DimPublishers AS DP
ON DT.PublisherKey = DP.PublisherKey
WHERE
@ShowAll = 'True'
OR (
DD.[Date] BETWEEN @StartDate AND @EndDate
AND DT.TitleId LIKE @Prefix
)
GROUP BY
DP.PublisherName
, DT.TitleName
, DT.TitleId
, DD.[Date]
ORDER BY DP.PublisherName, [Title], [OrderDate];
4️⃣ Key Performance Indicators (KPIs) in Relational SQL
While SSAS Multidimensional cubes compute KPIs in MDX space, relational reporting layers calculate KPI status thresholds directly in T-SQL using subqueries paired with conditional CASE expressions:
-
Subquery Baseline: Calculates a global aggregate benchmark (e.g., overall average sales quantity across the entire fact table) rather than the local group average.
-
Discrete Statistical Scale: Assigns standardized status indicator tokens:
- Underperforming (Off Target / Red)
- Baseline / Within Tolerance (Warning / Yellow)
- Exceeding Expectations (On Target / Green)
DECLARE @AverageQty int;
SELECT @AverageQty = AVG(SalesQuantity) FROM DWPubsSales.dbo.FactSales;
-- Inside SELECT list:
[Average Qty in the FactSales Table] = @AverageQty,
[KPI on Avg Quantity] = CASE
WHEN SUM(FS.SalesQuantity) BETWEEN (@AverageQty - 5) AND (@AverageQty + 5) THEN 0
WHEN SUM(FS.SalesQuantity) < (@AverageQty - 5) THEN -1
WHEN SUM(FS.SalesQuantity) > (@AverageQty + 5) THEN 1
END
5️⃣ Abstraction Layers: Views vs. Stored Procedures
Direct querying of base warehouse tables exposes physical schemas to breaking changes and complicates security governance. SQL Server provides two primary abstraction layers:
| Architectural Dimension | SQL Views (CREATE VIEW) |
Stored Procedures (CREATE PROCEDURE) |
|---|---|---|
| Execution Paradigm | Saved SELECT statement referenced like a virtual table. |
Compiled, procedural batch containing multiple statements, logic, and control-of-flow. |
| Parameter Support | No: Cannot accept input parameters or declare variables. | Yes: Fully supports typed input parameters with default fallback values. |
| Ordering Restrictions | Cannot contain ORDER BY unless TOP or OFFSET is specified. |
Fully supports ORDER BY for presentation-ready row sorting. |
| Subqueries & Procedural Logic | Limited: Cannot pre-populate procedural variables via separate queries. | Fully supports pre-execution subqueries, temporary tables, and dynamic SQL. |
| Client Usability | Natively browsable in Microsoft Excel PivotTables and Power BI Import. | Ideal for paginated enterprise engines (SSRS, Power BI Paginated Reports). |
6️⃣ Walkthrough of Hands-On Exercises
Exercise 13-1: Building an Aggregated Sales-by-Store Query
Construct a multi-table relational reporting query joining FactSales, DimStores, and DimDates to summarize total quantities ordered by store and date:
USE DWPubsSales;
GO
SELECT
DS.StoreName
, DS.StoreId
, [OrderDate] = CONVERT(varchar(50), DD.[Date], 101)
, [Total Qty by Store] = SUM(FS.SalesQuantity)
FROM DWPubsSales.dbo.FactSales AS FS
INNER JOIN DWPubsSales.dbo.DimStores AS DS
ON FS.StoreKey = DS.StoreKey
INNER JOIN DWPubsSales.dbo.DimDates AS DD
ON FS.OrderDateKey = DD.DateKey
GROUP BY
DS.StoreName
, DS.StoreId
, DD.[Date]
ORDER BY DS.StoreName, [OrderDate];
Exercise 13-2: Creating the Parameterized Store Stored Procedure
Encapsulate the store reporting query into a production stored procedure (pSelQuantitiesByStoreAndDate) supporting dynamic date-range filtering with defaults:
USE DWPubsSales;
GO
CREATE OR ALTER PROCEDURE pSelQuantitiesByStoreAndDate
(
@ShowAll nvarchar(4) = 'True'
, @StartDate datetime = '1990-01-01'
, @EndDate datetime = '2100-01-01'
)
AS
/*******************************************************************************
Title: pSelQuantitiesByStoreAndDate
Description: Returns summarized sales quantities by store and order date.
Developer: Your Name
Date: 2026-11-10
*******************************************************************************/
BEGIN
SET NOCOUNT ON;
SELECT
DS.StoreName
, [Stor] = DS.StoreId
, [OrderDate] = CONVERT(varchar(50), DD.[Date], 101)
, [Total Qty by St...] = SUM(FS.SalesQuantity)
FROM DWPubsSales.dbo.FactSales AS FS
INNER JOIN DWPubsSales.dbo.DimStores AS DS
ON FS.StoreKey = DS.StoreKey
INNER JOIN DWPubsSales.dbo.DimDates AS DD
ON FS.OrderDateKey = DD.DateKey
WHERE
@ShowAll = 'True'
OR (DD.[Date] BETWEEN @StartDate AND @EndDate)
GROUP BY
DS.StoreName
, DS.StoreId
, DD.[Date]
ORDER BY DS.StoreName, DD.[Date];
END;
GO
-- Verification Test Call:
EXEC pSelQuantitiesByStoreAndDate
@ShowAll = 'False'
, @StartDate = '1994-09-13'
, @EndDate = '1994-09-14';
7️⃣ References & Further Reading
-
Primary Course Text:Root, R., & Mason, C. (2012). Chapter 13: Creating Reports with SQL Queries. In Pro SQL Server 2012 BI Solutions (pp. 529–564).
-
T-SQL Query Architecture:Sack, J. (2008). SQL Server 2008 Transact-SQL Recipes: A Problem-Solution Approach.
-
Enterprise Reporting Architecture:Turley, P., & Bruckner, R. (2012). Professional SQL Server 2012 Reporting Services. John Wiley & Sons.