WINDOW FUNCTIONS ARE YOUR FRIENDS Dejan Dular @dejandular dejan.dular@gmail.com Dejan Dular SQL Grillen, Lingen, 2017
Dejan Dular s.p. Dejan Dular Dejan Dular Dejan Dular Developer CEO CFO .NET Developer SQL Developer Dynamics CRM specialist Dejan Dular CEO Dejan Dular CFO
SUM(quantity) OVER (<this set of rows>) Betsy
SUM(quantity) OVER (<partition> <order> <frame>) Betsy
SELECT S.TerritoryID, P.FirstName, P.LastName, S.SalesYTD, ROW_NUMBER() OVER (PARTITION BY S.TerritoryId ORDER BY S.SalesYTD) FROM Sales.SalesPerson S JOIN Person.Person P ON S.BusinessEntityID = P.BusinessEntityID ORDER TerritoryID FirstName LastName SalesYTD Row Number 1 Pamela Ansman-Wolfe 1.352.577,13 David Campbell 1.573.012,94 2 Tete Mensa-Annan 1.576.562,20 3 Michael Blythe 3.763.178,18 Jillian Carson 3.189.418,37 4 Shu Ito 2.458.535,62 Linda Mitchell 4.251.368,55 PARTITION Buttercup
Available functions Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE Magic castle
Available functions Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE Aggregates: SUM, AVG, MIN, MAX, COUNT, COUNT_BIG, STDEV, STDEVP, VAR, VARP Magic castle
Available functions Ranking: ROW_NUMBER, RANK, DENSE_RANK, NTILE Aggregates: SUM, AVG, MIN, MAX, COUNT, COUNT_BIG, STDEV, STDEVP, VAR, VARP Analytic: FIRST_VALUE, LAST_VALUE, LAG, LEAD, PERCENT_RANK, CUME_DIST, PERCENTILE_CONT, PERCENTILE_DIST Magic castle
FRAMING Sarka Year Month Sales 2016 1 1.352.577,13 2 1.573.012,94 3 1.576.562,20 4 3.063.178,18 5 3.189.418,37 6 2.458.535,62 7 4.251.368,55 Sarka
FRAMING ROWS (Physical operator) n PRECEEDING n FOLLLOWING UNBOUNDED PRECEEDING UNBOUNDED FOLLOWING CURRENT ROW
1 2 3 4 5 6 7 8 9 10 ROWS CURRENT ROW UNBOUNDED PRECEEDING 1 2 3 4 5 6 7 8 9 10 UNBOUNDED PRECEEDING UNBOUNDED FOLLOWING 2 PRECEEDING 3 FOLLOWING 1 FOLLOWING UNBOUNDED FOLLOWING Rob
FRAMING ROWS (Physical operator) n PRECEEDING n FOLLLOWING UNBOUNDED PRECEEDING UNBOUNDED FOLLOWING CURRENT ROW RANGE (Logical operator) CURRENT ROW (what is current row?)
RANGE CURRENT ROW ROW 1 2 3 4 5 6 7 8 9 10 DATA 10 20 30 30 30 30 40 40 60 70 UNBOUNDED PRECEEDING UNBOUNDED FOLLOWING Charlie
Martha the Unicorn says: Always define the window range to prevent invisible bugs in your queries
Performance LEAF INDEX SELECT SUM(Sales) OVER (PARTITION BY Year ORDER BY Month ROWS UNBOUNDED PRECEDING) LEAF INDEX Lightning
Using window functions like a boss! German sausage is the Wurst BUT! Austrian schnitzel is the Wiener! Using window functions like a boss!