SlideShare uma empresa Scribd logo
1 de 23
Edit

Simplifying and improving your SQL with

CTE’s and Windowing Functions

Clayton Groom

11/15/2013
t: cgroom or SQLMonger
cgroom@mailctp.com
www.geekswithblogs.net/sqlmonger
http://www.linkedin.com/in/claytongroom/
Platinum
Sponsors

Gold
Sponsors

Silver Sponsors
Agenda
SQL Basics
Think in Sets
Baseline performance
Save EVERYTHING as you develop (WIP)
Learn what is new and refactor old code

Examples/Scenarios
Begin with the end in mind
–

An example

Common Table Expressions
Windowing functions’

Questions?
Objective
Introduce you to new T-SQL language features you are probably not using…

Think in sets
Get your feet wet with new T-SQL functionality
Common Table Expressions (CTE’s)
Windowing functions
Teach SQL-only techniques for aggregation
Rolling aggregates
MTD, QTD, YTD, Same Period PY, etc.

4
Think in Sets
Improve your SQL Skills to improve your applications
Procedural approaches are out
– Cursors should almost never be used
– Existing cursor can be “fixed” by changing to the best cursor
type for the situation.
Diagram your queries before you write them
– Venn
– Tree
Set based approaches include:
– Correlated sub queries
– Common Table Expressions (CTE’s)
– MERGE operator
– Outer Apply
5
Think in Sets
Some great authors…

6
SQL Development 101
Baseline performance
Use DBCC FREEPROCCACHE to clear the procedure cache and
provide solid baseline results
Use Statistics IO and Statistics Time to capture query stats.
SET STATISTICS IO ON;
SET STATISTICS TIME ON;

Keep versions of your code, with timings
– Database performance will change as data grows
– Having the options you have already tried available
– May be applicable to different situations

7
Common Table Expressions (CTE’s)
ANSI standard way to avoid temp tables

CTE’s are table results objects defined within the scope of a single
statement.
• Use CTE’s in place of Temp tables
• Aggregate results for following steps
• Use CTE to substitute for a VIEW or #temp table
• Enable GROUP BY on derive columns
• Support Recursive joins
• More readable, easier to maintain code – building block approach.
Limitations:
• GROUP BY, HAVING, or aggregate functions are not allowed in the recursive
part of a recursive common table expression
•

Outer joins are not allowed in the recursive part of a recursive common
table expression
8
CTE Example
Simple example – Calculate Total and Percent of Total
WITH CTE_Totals
AS (SELECT CustomerKey
,SUM(SalesAmount) AS [Total Cust Sales Amt]
FROM [dbo].[FactInternetSales]
WHERE CustomerKey IN (15954, 27052, 23808)
GROUP BY CustomerKey
)
SELECT f.CustomerKey
, f.ProductKey
, f.SalesAmount
,t.[Total Cust Sales Amt]
,f.SalesAmount / t.[Total Cust Sales Amt]
as [Pct of Total]
FROM [dbo].[FactInternetSales] AS f
INNER JOIN CTE_Totals t
ON f.CustomerKey = t.CustomerKey
WHERE f.CustomerKey IN (15954, 27052, 23808)
9
Demo - Common Table Expression
I will post the examples to my SkyDrive and have a link on my Blog. I will be updating the examples
as I come across useful applications. http://sdrv.ms/HZtKYP

10
Windowing functions
Supported Windowing Elements

Function_name(<arguments.) OVER(
[<PARTITION BY clause>]
[<ORDER BY clause>
[<ROW or RANGE clause>] ] )

11
Windowing function Example
Simple example – Calculate Total and Percent of Total
SELECT CustomerKey
,ProductKey
,SalesAmount
,SUM(SalesAmount)
OVER(PARTITION BY CustomerKey)
AS [Cust Sales Amt]
,SUM(SalesAmount)
OVER() AS [Total Sales Amt]
,cast(100.0 * SalesAmount/SUM(SalesAmount)
OVER(PARTITION BY CustomerKey)
as numeric(5,2)) as [Pct of Cust Total]
,cast(100.0 * SalesAmount/SUM(SalesAmount)
OVER()
as numeric(5,2)) as [Pct of Total]
FROM [dbo].[FactInternetSales]
WHERE CustomerKey IN (15954, 27052, 23808)
order by 1,2;
12
Window Partition Clause
Sets the “frame” or subset of the rows that will be accessible to the
windowing function

13
Window Order Clause
Orders the rows within the Partitioning frame
Required for the ROW and RANGE operators

14
Window Framing Clause
Selects rows within a frame, relative to the current row
Requires an ORDER BY clause
sum(sum(f.SalesAmount) )
OVER(PARTITION BY f.productkey, year(f.orderdate),
Month(f.orderdate)
ORDER BY f.productkey, f.orderdate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) as [Sales Amt MTD]
4
Unbounded
Preceding

3

2

1

0

1

Current
Row

2

3
Unbounded
Following

15
Window Framing Clause
Supported Options
ROWS UNBOUNDED PRECEDING
ROWS <unsigned integer literal> PRECEDING
ROWS CURRENT ROW
ROWS BETWEEN UNBOUNDED PRECEDING AND <unsigned integer literal> PRECEDING
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
ROWS BETWEEN UNBOUNDED PRECEDING AND <unsigned integer literal> FOLLOWING
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
ROWS BETWEEN <unsigned integer literal> PRECEDING AND <unsigned integer literal> PRECEDING
ROWS BETWEEN <unsigned integer literal> PRECEDING AND CURRENT ROW
ROWS BETWEEN <unsigned integer literal> PRECEDING AND <unsigned integer literal> FOLLOWING
ROWS BETWEEN <unsigned integer literal> PRECEDING AND UNBOUNDED FOLLOWING
ROWS BETWEEN CURRENT ROW AND CURRENT ROW
ROWS BETWEEN CURRENT ROW AND <unsigned integer> FOLLOWING
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
ROWS BETWEEN <unsigned integer literal> FOLLOWING AND <unsigned integer> FOLLOWING
ROWS BETWEEN <unsigned integer literal> FOLLOWING AND UNBOUNDED FOLLOWING
RANGE UNBOUNDED PRECEDING
RANGE CURRENT ROW
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
RANGE BETWEEN CURRENT ROW AND CURRENT ROW

RANGE uses a count of distinct values, where ROWS uses the count of the
rows. Rows with the a “TIE” based on the Order By clause will be merged.
16
Windowing Functions - Aggregate
Aggregate Functions that can be used with the OVER Clause

AVG()
CHECKSUM_AGG() - Checksum of values in a group
COUNT(), COUNT_BIG()
MAX()
MIN()
SUM()
STDEV()
STDEVP()
VAR()
VARP()
17
Windowing Functions - Ranking
Ranking functions

RANK()
DENSE_RANK()
NTILE()
ROW_NUMBER()

-

18
Windowing Functions - Analytic
Analytic functions

CUME_DIST()
FIRST_VALUE()
LAST_VALUE()
LEAD()
LAG()
PERCENTILE_CONT()
PERCENTILE_DISC()
PERCENT_RANK()

- Cumulative Distribution
- First value within the ordered partition
- Last value within the ordered partition
- Returns a following value based on an offset
- Returns a prior value based on an offset
- Percentile based on a continuous distribution
- Percentile based on discreet column values
- Relative rank of a row within a group of rows

19
Other new Functions
Aggregate Functions that can be used with the OVER Clause

GROUPING()
GROUPING_ID()

- Replaces the COMPUTE clause
- And gives us some new capabilities

20
Demonstrations
I will post the examples to my SkyDrive and have a link on my Blog. I will be updating the examples
as I come across useful applications. http://sdrv.ms/HZtKYP

21
References
Windows Functions in SQL
https://www.simple-talk.com/sql/t-sql-programming/window-functions-in-sql/
Working with Window Functions in SQL Server

https://www.simple-talk.com/sql/learn-sql-server/working-with-window-functions-in-sqlserver/
SQL Server 2012 Windowing Functions Part 1 of 2: Running and Sliding Aggregates
http://lennilobel.wordpress.com/tag/t-sql-running-aggregates/
SQL Server Books Online – Over Clause
http://technet.microsoft.com/en-us/library/ms189461.aspx

22
Questions?

Mais conteúdo relacionado

Mais procurados

Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle SqlAhmed Yaseen
 
Chetan postgresql partitioning
Chetan postgresql partitioningChetan postgresql partitioning
Chetan postgresql partitioningOpenSourceIndia
 
Advanced functions in PL SQL
Advanced functions in PL SQLAdvanced functions in PL SQL
Advanced functions in PL SQLHosein Zare
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraintsVineeta Garg
 
Firebird 3 Windows Functions
Firebird 3 Windows  FunctionsFirebird 3 Windows  Functions
Firebird 3 Windows FunctionsMind The Firebird
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and OperatorsMohan Kumar.R
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?Andrej Pashchenko
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functionsVineeta Garg
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsAndrej Pashchenko
 
Presentation top tips for getting optimal sql execution
Presentation    top tips for getting optimal sql executionPresentation    top tips for getting optimal sql execution
Presentation top tips for getting optimal sql executionxKinAnx
 
Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4HighLoad2009
 

Mais procurados (20)

Introduction To Oracle Sql
Introduction To Oracle SqlIntroduction To Oracle Sql
Introduction To Oracle Sql
 
Chetan postgresql partitioning
Chetan postgresql partitioningChetan postgresql partitioning
Chetan postgresql partitioning
 
Advanced functions in PL SQL
Advanced functions in PL SQLAdvanced functions in PL SQL
Advanced functions in PL SQL
 
Single row functions
Single row functionsSingle row functions
Single row functions
 
Structured query language constraints
Structured query language constraintsStructured query language constraints
Structured query language constraints
 
Firebird 3 Windows Functions
Firebird 3 Windows  FunctionsFirebird 3 Windows  Functions
Firebird 3 Windows Functions
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
MERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known FacetsMERGE SQL Statement: Lesser Known Facets
MERGE SQL Statement: Lesser Known Facets
 
Presentation top tips for getting optimal sql execution
Presentation    top tips for getting optimal sql executionPresentation    top tips for getting optimal sql execution
Presentation top tips for getting optimal sql execution
 
Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4Performance Enhancements In Postgre Sql 8.4
Performance Enhancements In Postgre Sql 8.4
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 

Semelhante a Simplifying SQL with CTE's and windowing functions

Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdfKalyankumarVenkat1
 
Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data ScientistsDatabricks
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOAltinity Ltd
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...Altinity Ltd
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
 
Column store indexes and batch processing mode (nx power lite)
Column store indexes and batch processing mode (nx power lite)Column store indexes and batch processing mode (nx power lite)
Column store indexes and batch processing mode (nx power lite)Chris Adkin
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1MariaDB plc
 
You might be paying too much for BigQuery
You might be paying too much for BigQueryYou might be paying too much for BigQuery
You might be paying too much for BigQueryRyuji Tamagawa
 
AWS July Webinar Series: Amazon Redshift Optimizing Performance
AWS July Webinar Series: Amazon Redshift Optimizing PerformanceAWS July Webinar Series: Amazon Redshift Optimizing Performance
AWS July Webinar Series: Amazon Redshift Optimizing PerformanceAmazon Web Services
 
Performance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondPerformance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondTomas Vondra
 
5.Analytical Function.pdf
5.Analytical Function.pdf5.Analytical Function.pdf
5.Analytical Function.pdfssuser8b6c85
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricksYanli Liu
 
Webinar: Secrets of ClickHouse Query Performance, by Robert Hodges
Webinar: Secrets of ClickHouse Query Performance, by Robert HodgesWebinar: Secrets of ClickHouse Query Performance, by Robert Hodges
Webinar: Secrets of ClickHouse Query Performance, by Robert HodgesAltinity Ltd
 
Run your queries 14X faster without any investment!
Run your queries 14X faster without any investment!Run your queries 14X faster without any investment!
Run your queries 14X faster without any investment!Knoldus Inc.
 
Fun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfFun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfAltinity Ltd
 
Fun with click house window functions webinar slides 2021-08-19
Fun with click house window functions webinar slides  2021-08-19Fun with click house window functions webinar slides  2021-08-19
Fun with click house window functions webinar slides 2021-08-19Altinity Ltd
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 

Semelhante a Simplifying SQL with CTE's and windowing functions (20)

Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdf
 
Advanced SQL For Data Scientists
Advanced SQL For Data ScientistsAdvanced SQL For Data Scientists
Advanced SQL For Data Scientists
 
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEOClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
ClickHouse Query Performance Tips and Tricks, by Robert Hodges, Altinity CEO
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...
Webinar slides: MORE secrets of ClickHouse Query Performance. By Robert Hodge...
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
Column store indexes and batch processing mode (nx power lite)
Column store indexes and batch processing mode (nx power lite)Column store indexes and batch processing mode (nx power lite)
Column store indexes and batch processing mode (nx power lite)
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 
You might be paying too much for BigQuery
You might be paying too much for BigQueryYou might be paying too much for BigQuery
You might be paying too much for BigQuery
 
AWS July Webinar Series: Amazon Redshift Optimizing Performance
AWS July Webinar Series: Amazon Redshift Optimizing PerformanceAWS July Webinar Series: Amazon Redshift Optimizing Performance
AWS July Webinar Series: Amazon Redshift Optimizing Performance
 
Performance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyondPerformance improvements in PostgreSQL 9.5 and beyond
Performance improvements in PostgreSQL 9.5 and beyond
 
5.Analytical Function.pdf
5.Analytical Function.pdf5.Analytical Function.pdf
5.Analytical Function.pdf
 
Oracle tips and tricks
Oracle tips and tricksOracle tips and tricks
Oracle tips and tricks
 
Webinar: Secrets of ClickHouse Query Performance, by Robert Hodges
Webinar: Secrets of ClickHouse Query Performance, by Robert HodgesWebinar: Secrets of ClickHouse Query Performance, by Robert Hodges
Webinar: Secrets of ClickHouse Query Performance, by Robert Hodges
 
Anything SQL: Lightning Talks
Anything SQL: Lightning TalksAnything SQL: Lightning Talks
Anything SQL: Lightning Talks
 
Run your queries 14X faster without any investment!
Run your queries 14X faster without any investment!Run your queries 14X faster without any investment!
Run your queries 14X faster without any investment!
 
Fun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdfFun with ClickHouse Window Functions-2021-08-19.pdf
Fun with ClickHouse Window Functions-2021-08-19.pdf
 
Fun with click house window functions webinar slides 2021-08-19
Fun with click house window functions webinar slides  2021-08-19Fun with click house window functions webinar slides  2021-08-19
Fun with click house window functions webinar slides 2021-08-19
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 

Último

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Último (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Simplifying SQL with CTE's and windowing functions

  • 1. Edit Simplifying and improving your SQL with CTE’s and Windowing Functions Clayton Groom 11/15/2013 t: cgroom or SQLMonger cgroom@mailctp.com www.geekswithblogs.net/sqlmonger http://www.linkedin.com/in/claytongroom/
  • 3. Agenda SQL Basics Think in Sets Baseline performance Save EVERYTHING as you develop (WIP) Learn what is new and refactor old code Examples/Scenarios Begin with the end in mind – An example Common Table Expressions Windowing functions’ Questions?
  • 4. Objective Introduce you to new T-SQL language features you are probably not using… Think in sets Get your feet wet with new T-SQL functionality Common Table Expressions (CTE’s) Windowing functions Teach SQL-only techniques for aggregation Rolling aggregates MTD, QTD, YTD, Same Period PY, etc. 4
  • 5. Think in Sets Improve your SQL Skills to improve your applications Procedural approaches are out – Cursors should almost never be used – Existing cursor can be “fixed” by changing to the best cursor type for the situation. Diagram your queries before you write them – Venn – Tree Set based approaches include: – Correlated sub queries – Common Table Expressions (CTE’s) – MERGE operator – Outer Apply 5
  • 6. Think in Sets Some great authors… 6
  • 7. SQL Development 101 Baseline performance Use DBCC FREEPROCCACHE to clear the procedure cache and provide solid baseline results Use Statistics IO and Statistics Time to capture query stats. SET STATISTICS IO ON; SET STATISTICS TIME ON; Keep versions of your code, with timings – Database performance will change as data grows – Having the options you have already tried available – May be applicable to different situations 7
  • 8. Common Table Expressions (CTE’s) ANSI standard way to avoid temp tables CTE’s are table results objects defined within the scope of a single statement. • Use CTE’s in place of Temp tables • Aggregate results for following steps • Use CTE to substitute for a VIEW or #temp table • Enable GROUP BY on derive columns • Support Recursive joins • More readable, easier to maintain code – building block approach. Limitations: • GROUP BY, HAVING, or aggregate functions are not allowed in the recursive part of a recursive common table expression • Outer joins are not allowed in the recursive part of a recursive common table expression 8
  • 9. CTE Example Simple example – Calculate Total and Percent of Total WITH CTE_Totals AS (SELECT CustomerKey ,SUM(SalesAmount) AS [Total Cust Sales Amt] FROM [dbo].[FactInternetSales] WHERE CustomerKey IN (15954, 27052, 23808) GROUP BY CustomerKey ) SELECT f.CustomerKey , f.ProductKey , f.SalesAmount ,t.[Total Cust Sales Amt] ,f.SalesAmount / t.[Total Cust Sales Amt] as [Pct of Total] FROM [dbo].[FactInternetSales] AS f INNER JOIN CTE_Totals t ON f.CustomerKey = t.CustomerKey WHERE f.CustomerKey IN (15954, 27052, 23808) 9
  • 10. Demo - Common Table Expression I will post the examples to my SkyDrive and have a link on my Blog. I will be updating the examples as I come across useful applications. http://sdrv.ms/HZtKYP 10
  • 11. Windowing functions Supported Windowing Elements Function_name(<arguments.) OVER( [<PARTITION BY clause>] [<ORDER BY clause> [<ROW or RANGE clause>] ] ) 11
  • 12. Windowing function Example Simple example – Calculate Total and Percent of Total SELECT CustomerKey ,ProductKey ,SalesAmount ,SUM(SalesAmount) OVER(PARTITION BY CustomerKey) AS [Cust Sales Amt] ,SUM(SalesAmount) OVER() AS [Total Sales Amt] ,cast(100.0 * SalesAmount/SUM(SalesAmount) OVER(PARTITION BY CustomerKey) as numeric(5,2)) as [Pct of Cust Total] ,cast(100.0 * SalesAmount/SUM(SalesAmount) OVER() as numeric(5,2)) as [Pct of Total] FROM [dbo].[FactInternetSales] WHERE CustomerKey IN (15954, 27052, 23808) order by 1,2; 12
  • 13. Window Partition Clause Sets the “frame” or subset of the rows that will be accessible to the windowing function 13
  • 14. Window Order Clause Orders the rows within the Partitioning frame Required for the ROW and RANGE operators 14
  • 15. Window Framing Clause Selects rows within a frame, relative to the current row Requires an ORDER BY clause sum(sum(f.SalesAmount) ) OVER(PARTITION BY f.productkey, year(f.orderdate), Month(f.orderdate) ORDER BY f.productkey, f.orderdate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) as [Sales Amt MTD] 4 Unbounded Preceding 3 2 1 0 1 Current Row 2 3 Unbounded Following 15
  • 16. Window Framing Clause Supported Options ROWS UNBOUNDED PRECEDING ROWS <unsigned integer literal> PRECEDING ROWS CURRENT ROW ROWS BETWEEN UNBOUNDED PRECEDING AND <unsigned integer literal> PRECEDING ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ROWS BETWEEN UNBOUNDED PRECEDING AND <unsigned integer literal> FOLLOWING ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ROWS BETWEEN <unsigned integer literal> PRECEDING AND <unsigned integer literal> PRECEDING ROWS BETWEEN <unsigned integer literal> PRECEDING AND CURRENT ROW ROWS BETWEEN <unsigned integer literal> PRECEDING AND <unsigned integer literal> FOLLOWING ROWS BETWEEN <unsigned integer literal> PRECEDING AND UNBOUNDED FOLLOWING ROWS BETWEEN CURRENT ROW AND CURRENT ROW ROWS BETWEEN CURRENT ROW AND <unsigned integer> FOLLOWING ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ROWS BETWEEN <unsigned integer literal> FOLLOWING AND <unsigned integer> FOLLOWING ROWS BETWEEN <unsigned integer literal> FOLLOWING AND UNBOUNDED FOLLOWING RANGE UNBOUNDED PRECEDING RANGE CURRENT ROW RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING RANGE BETWEEN CURRENT ROW AND CURRENT ROW RANGE uses a count of distinct values, where ROWS uses the count of the rows. Rows with the a “TIE” based on the Order By clause will be merged. 16
  • 17. Windowing Functions - Aggregate Aggregate Functions that can be used with the OVER Clause AVG() CHECKSUM_AGG() - Checksum of values in a group COUNT(), COUNT_BIG() MAX() MIN() SUM() STDEV() STDEVP() VAR() VARP() 17
  • 18. Windowing Functions - Ranking Ranking functions RANK() DENSE_RANK() NTILE() ROW_NUMBER() - 18
  • 19. Windowing Functions - Analytic Analytic functions CUME_DIST() FIRST_VALUE() LAST_VALUE() LEAD() LAG() PERCENTILE_CONT() PERCENTILE_DISC() PERCENT_RANK() - Cumulative Distribution - First value within the ordered partition - Last value within the ordered partition - Returns a following value based on an offset - Returns a prior value based on an offset - Percentile based on a continuous distribution - Percentile based on discreet column values - Relative rank of a row within a group of rows 19
  • 20. Other new Functions Aggregate Functions that can be used with the OVER Clause GROUPING() GROUPING_ID() - Replaces the COMPUTE clause - And gives us some new capabilities 20
  • 21. Demonstrations I will post the examples to my SkyDrive and have a link on my Blog. I will be updating the examples as I come across useful applications. http://sdrv.ms/HZtKYP 21
  • 22. References Windows Functions in SQL https://www.simple-talk.com/sql/t-sql-programming/window-functions-in-sql/ Working with Window Functions in SQL Server https://www.simple-talk.com/sql/learn-sql-server/working-with-window-functions-in-sqlserver/ SQL Server 2012 Windowing Functions Part 1 of 2: Running and Sliding Aggregates http://lennilobel.wordpress.com/tag/t-sql-running-aggregates/ SQL Server Books Online – Over Clause http://technet.microsoft.com/en-us/library/ms189461.aspx 22

Notas do Editor

  1. Sample files will be posted shortly on my blog/skydrive
  2. Draw out a tree of the tables and their relationships, and what fields you need from each. Plan out any pre-aggregations needed that can be handled as CTE’s, limit results from joins etc.
  3. SQL Geek dilemma: Do I like Kirk or do I like Picard… Can’t recommend these guys books enough. Joe Celko’s SQL Puzzles in DBMS magazine were what really got my career in SQL development started.
  4. Allow for the creation of sliding windows across the rows in the frame, which enables all kinds of possibilities!
  5. RANGE uses a count of distinct values, where ROWS uses the count of the rows. Rows with the a “TIE” based on the Order By clause will be merged.Note that Azure Database (SQL Azure) does not fully support the SQL 2012 windowing functions yet.