Foreword
Introduction
SQL Windowing
Background of Window Functions
Window Functions Described
Set-Based vs. Iterative/Cursor Programming
Drawbacks of Alternatives to Window Functions
A Glimpse of Solutions Using Window Functions
Elements of Window Functions
Partitioning
Ordering
Framing
Query Elements Supporting Window Functions
Logical Query Processing
Clauses Supporting Window Functions
Circumventing the Limitations
Potential for Additional Filters
Reuse of Window Definitions
Summary
A Detailed Look at Window Functions
Window Aggregate Functions
Window Aggregate Functions Described
Supported Windowing Elements
Further Filtering Ideas
Distinct Aggregates
Nested Aggregates
Ranking Functions
Supported Windowing Elements
ROW_NUMBER
NTILE
RANK and DENSE_RANK
Distribution Functions
Supported Windowing Elements
Rank Distribution Functions
Inverse Distribution Functions
Offset Functions
Supported Windowing Elements
LAG and LEAD
FIRST_VALUE, LAST_VALUE, and NTH_VALUE
Summary
Ordered Set Functions
Hypothetical Set Functions
RANK
DENSE_RANK
PERCENT_RANK
CUME_DIST
General Solution
Inverse Distribution Functions
Offset Functions
String Concatenation
Summary
Optimization of Window Functions
Sample Data
Indexing Guidelines
POC Index
Backward Scans
Columnstore Indexes
Ranking Functions
ROW_NUMBER
NTILE
RANK and DENSE_RANK
Improved Parallelism with APPLY
Aggregate and Offset Functions
Without Ordering and Framing
With Ordering and Framing
Distribution Functions
Rank Distribution Functions
Inverse Distribution Functions
Summary
T-SQL Solutions Using Window Functions
Virtual Auxiliary Table of Numbers
Sequences of Date and Time Values
Sequences of Keys
Update a Column with Unique Values
Applying a Range of Sequence Values
Paging
Removing Duplicates
Pivoting
TOP N per Group
Mode
Running Totals
Set-Based Solution Using Window Functions
Set-Based Solutions Using Subqueries or Joins
Cursor-Based Solution
CLR-Based Solution
Nested Iterations
Multirow UPDATE with Variables
Performance Benchmark
Max Concurrent Intervals
Traditional Set-Based Solution
Cursor-Based Solution
Solutions Based on Window Functions
Performance Benchmark
Packing Intervals
Traditional Set-Based Solution
Solutions Based on Window Functions
Gaps and Islands
Gaps
Islands
Median
Conditional Aggregate
Sorting Hierarchies
Summary
Index