250 likes | 357 Views
Writing Better Queries with Window Functions. Who am I?. Kathi Kellenberger, MVP Pragmatic Works www.bidn.com/blogs/kathikellenberger kkellenberger@pragmaticworks.com @ auntkathi. Teaching SSRS and SSRS Master Classes.
E N D
Who am I? Kathi Kellenberger, MVPPragmatic Workswww.bidn.com/blogs/kathikellenbergerkkellenberger@pragmaticworks.com @auntkathi Teaching SSRS and SSRS Master Classes Beginning SSRS Joes 2 ProsBeginning T-SQL 2012Beginning T-SQL 2008SQL Server MVP Deep Dives (Vol 1)
History 2005: Window functions introduced 2012: Window functions enhanced Best resource: Microsoft SQL Server2012 High-Performance T-SQL Using Window Functions by Itzik Ben-Gan
What are window functions? • Ranking functions • Window aggregates • 2012 Enhancements: ORDER BY • 2012 Enhancements: Framing • Analytic functions Agenda Making Business Intelligent
What are window functions? Function performs over a SET (window of the results) How to identify a window function The OVER clause defines the window • Where to put window functions SELECT and ORDER BY clauses only • Important! The FROM, WHERE, GROUP BY and HAVING clauses operate BEFORE the window functions PartitionsNOT the same as GROUP BY
Ranking functions Available since 2005 ROW_NUMBER() A unique # over the window RANK() Deals with ties DENSE_RANK() Deals with ties NTILE() Divide rows into buckets
Ranking functions: Tuning Sequence Project Operator Index: Partition + Order by + Covering If there is a filter, add filter columns first Watch out for reverse directionor different ordering
Ranking Functions Demo
Window aggregate functions Your favorite aggregates with no GROUP BY Add aggregate function to a non-aggregate query Calculate over the window: the entire result set or partition Pre-2012 functionality NOT optimized for performance
Window Aggregates Demo
2012 enhancements ORDER BY clauseadded to window aggregates Performance optimization Even further define the window with ROWS and RANGE: FRAMING
Running Total Demo
FRAME: ROWS and RANGE Further define window Terms UNBOUNDED PRECEDING UNBOUNDED FOLLOWING CURRENT ROW # PRECEDING # FOLLOWING RANGE is not fully implementedand can hurt performance
Framing Rows between unbounded preceding and current row
Framing Rows between current row and unbounded following
Framing Rows between 2 preceding and current row
Framing Rows between 5 precedingand 2 following
Framing Demo
The Analytic Functions LAG() and LEAD()Look back or look forward FIRST_VALUE() and LAST_VALUE()The very first or very last PERCENT_RANK() and CUME_DIST()Calculate ranking PERCENTILE_DISC() and PERCENTILE_CONT()Given a percent, find the value
Analytic Functions Demo