SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Oracle SQL Analytic
Functions
BY MELINDA WEBSTER
Toy Retailer Example
create table purchases ( category varchar2( 100 ) not null, year_no number not null,
month_no number not null, sales number );
category year_no month_no sales
Action Figures 2014 1 $ 3,000
Action Figures 2014 2 $ 1,700
Action Figures 2014 3 $ 1,200
Action Figures 2014 4 $ 1,500
Action Figures 2014 5 $ 2,000
Action Figures 2014 6 $ 2,150
Dolls 2014 1 $ 200
Dolls 2014 2 $ 175
Dolls 2014 3 $ 400
Dolls 2014 4 $ 300
Dolls 2014 5 $ 350
…
Aggregate Functions
* Function used to group together data resulting in a total for that group
*Some examples:
* Sum
* Count
* Max
* Min
* Use “group by” clause to group rows together
* Don’t care to see all the rows that make up the total.
Aggregate - Sum
select category, month_no, sum( sales ) as sales
from purchases
group by category, month_no;
category month_no sales
Action Figures 1 $ 3,000
Dolls 1 $ 200
Plush 1 $ 1,000
Video Games 1 $ 1,000
Action Figures 2 $ 1,700
Dolls 2 $ 175
Plush 2 $ 300
…
Analytic Functions
* Introduced in Oracle v 8i
* Also known as windowing functions
* Use “partition by” clause to group rows together
* The last set of operations performed in a query, except for the order by clause.
* All joins, where, group by, and having clauses are completed before the analytic functions are
processed.
* Can only appear in the select list or order by clauses.
Why Analytic Functions?
* Why would you want to use Analytic Functions?
*Simplify your code.
*Code is easier to maintain and read.
*In the long run, type less. 
* Can use native joins and sub-queries to get the same results, but why would you, if you had a
simplier way to do the same thing?
Anatomy of Analytic Functions
<analytic function> ( [ arg1, … argn] )
OVER ( [ PARTITION BY expr1 [,…,expn] ]
[ ORDER BY expr1 [ , …., expn ] ]
<windowing clause> )
Analytic - Sum
select category, month_no, sales,
sum( sales ) over ( partition by category ) as ttl_cat_sales,
sum( sales ) over ( ) as ttl_sales
from purchases;
category month_no sales ttl category sales ttl sales
Action Figures 1 $ 3,000 $ 11,550 $ 26,075
Action Figures 2 $ 1,700 $ 11,550 $ 26,075
Action Figures 3 $ 1,200 $ 11,550 $ 26,075
Action Figures 4 $ 1,500 $ 11,550 $ 26,075
Action Figures 5 $ 2,000 $ 11,550 $ 26,075
Action Figures 6 $ 2,150 $ 11,550 $ 26,075
Dolls 1 $ 200 $ 1,825 $ 26,075
Dolls 2 $ 175 $ 1,825 $ 26,075
…
Anatomy of Rank, dense_rank,
row_number
RANK | DENSE_RANK | ROW_NUMBER ( [ arg1, … argn] )
OVER ( [ PARTITION BY expr1 [,…,expn] ]
ORDER BY expr1 [ , …., expn ] )
Difference between Rank, dense_rank,
row_number
All
* serial number for each row based on some column or expression.
Rank
* If 2 rows have the same value (N), they receive the same sequential value of N, and the next
value N+1 will be skipped and the N+2 value will be given to the next record.
Dense_rank
* If 2 rows have the same value (N), it does not skip position N+1.
Row_number
* running serial number to the partition records based on the order by clause.
Rank, Dense_rank, Row_number
select month_no, category, sales,
row_number( ) over ( partition by month_no order by sales desc ) as row_no,
rank( ) over ( partition by month_no order by sales desc ) as rank_no,
dense_rank( ) over ( partition by month_no order by sales desc ) as dense_rank_no
from purchases;
month_no category sales row_no rank_no dense_rank_no
1Action Figures $ 3,000 1 1 1
1Plush $ 1,000 2 2 2
1Video Games $ 1,000 3 2 2
1Dolls $ 200 4 4 3
2Action Figures $ 1,700 1 1 1
2Video Games $ 500 2 2 2
2Plush $ 300 3 3 3
2Dolls $ 175 4 4 4
…
Anatomy of Ratio_to_report
RATIO_TO_REPORT ( [ arg1, … argn] )
OVER ( [ PARTITION BY expr1 [,…,expn] ]
ORDER BY expr1 [ , …., expn ] )
Ratio_to_report
select month_no, category, sales,
round( ratio_to_report( sales) over ( partition by month_no ) , 2 ) as ratio
from purchases;
month_nof category sales ratio
1Action Figures $ 3,000 0.58
1Video Games $ 1,000 0.19
1Plush $ 1,000 0.19
1Dolls $ 200 0.04
2Action Figures $ 1,700 0.64
2Video Games $ 500 0.19
2Plush $ 300 0.11
2Dolls $ 175 0.07
3Video Games $ 1,500 0.43
Lag and Lead
* Provides access to more than one row of a table at the same time without a self join
* Lag – access to data from a prior row.
* Lead – access to data from a following row.
* Examples:
* To compare prior value to current record value
* Compare prices of items to see if the item was an increase/decrease
Lag/Lead
select month_no, category, sales
,lag( sales) over ( partition by category order by month_no) as prior_mth_sales
,lead( sales) over ( partition by category order by month_no) as next_mth_sales
from purchases;
month_no category sales prior_mth_sales next_mth_sales
1Action Figures $ 3,000 $ 1,700
2Action Figures $ 1,700 $ 3,000 $ 1,200
3Action Figures $ 1,200 $ 1,700 $ 1,500
4Action Figures $ 1,500 $ 1,200 $ 2,000
5Action Figures $ 2,000 $ 1,500 $ 2,150
6Action Figures $ 2,150 $ 2,000
1Dolls $ 200 $ 175
2Dolls $ 175 $ 200 $ 400
3Dolls $ 400 $ 175 $ 300
Windowing Clause
* Windowing definition is a group of rows defined in the windowing clause.
* A sliding window of rows is defined for each row
* The window determines the range of rows used to perform the calculations for the current row.
* Window sizes can be based on either physical number of rows or a logical interval such as time.
* Windowing clause examples:
* UNBOUNDED PRECEDING : The window starts at the first row of the partition. Only available
for start points.
* UNBOUNDED FOLLOWING : The window ends at the last row of the partition. Only available
for end points.
* CURRENT ROW : The window starts or ends at the current row. Can be used as start or end
point.
Anatomy of Windowing
<windowing_function_name > ( [ arg1, … argn] )
OVER ( [ PARTITION BY expr1 [,…,expn] ]
ORDER BY expr1 [ , …., expn ]
<windowing_clause>
)
Rolling Totals
select month_no, category, sales
,sum( sales) over ( partition by category order by month_no rows unbounded preceding )
as rolling_ttl
from purchases;
month_no category sales rolling_ttl
1Action Figures $ 3,000 $ 3,000
2Action Figures $ 1,700 $ 4,700
3Action Figures $ 1,200 $ 5,900
4Action Figures $ 1,500 $ 7,400
5Action Figures $ 2,000 $ 9,400
6Action Figures $ 2,150 $ 11,550
1Dolls $ 200 $ 200
2Dolls $ 175 $ 375
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQLEDB
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)Ankit Dubey
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankMd Mudassir
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsZohar Elkayam
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracleLogan Palanisamy
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functionsVikas Gupta
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggersrehaniltifat
 

Was ist angesagt? (20)

[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL[APJ] Common Table Expressions (CTEs) in SQL
[APJ] Common Table Expressions (CTEs) in SQL
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
SQL
SQLSQL
SQL
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
SQL select clause
SQL select clauseSQL select clause
SQL select clause
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question Bank
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Oracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic FunctionsOracle Advanced SQL and Analytic Functions
Oracle Advanced SQL and Analytic Functions
 
Analytic & Windowing functions in oracle
Analytic & Windowing functions in oracleAnalytic & Windowing functions in oracle
Analytic & Windowing functions in oracle
 
advanced sql(database)
advanced sql(database)advanced sql(database)
advanced sql(database)
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
AGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptxAGGREGATE FUNCTION.pptx
AGGREGATE FUNCTION.pptx
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
Sql commands
Sql commandsSql commands
Sql commands
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 

Ähnlich wie Oracle SQL Analytic Functions Explained

dplyr Package in R
dplyr Package in Rdplyr Package in R
dplyr Package in RVedant Shah
 
Company segmentation - an approach with R
Company segmentation - an approach with RCompany segmentation - an approach with R
Company segmentation - an approach with RCasper Crause
 
Enabling Applications with Informix' new OLAP functionality
 Enabling Applications with Informix' new OLAP functionality Enabling Applications with Informix' new OLAP functionality
Enabling Applications with Informix' new OLAP functionalityAjay Gupte
 
Olap Functions Suport in Informix
Olap Functions Suport in InformixOlap Functions Suport in Informix
Olap Functions Suport in InformixBingjie Miao
 
Assumptions: Check yo'self before you wreck yourself
Assumptions: Check yo'self before you wreck yourselfAssumptions: Check yo'self before you wreck yourself
Assumptions: Check yo'self before you wreck yourselfErin Shellman
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQLJulian Hyde
 
Procedure rol against retail raw data
Procedure rol against retail raw dataProcedure rol against retail raw data
Procedure rol against retail raw dataPalash Halder
 
cost II chapter 1.pptx
cost II chapter 1.pptxcost II chapter 1.pptx
cost II chapter 1.pptxZAKIRKASSAYE
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptxSabrinaShanta2
 
IT301-Datawarehousing (1) and its sub topics.pptx
IT301-Datawarehousing (1) and its sub topics.pptxIT301-Datawarehousing (1) and its sub topics.pptx
IT301-Datawarehousing (1) and its sub topics.pptxReneeClintGortifacio
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questionsPyadav010186
 
Engine90 crawford-decision-making (1)
Engine90 crawford-decision-making (1)Engine90 crawford-decision-making (1)
Engine90 crawford-decision-making (1)Divyansh Dokania
 
Getting Started with MDX 20140625a
Getting Started with MDX 20140625aGetting Started with MDX 20140625a
Getting Started with MDX 20140625aRon Moore
 
Divide and Be Conquered?
Divide and Be Conquered?Divide and Be Conquered?
Divide and Be Conquered?brooksaix
 
I really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfI really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfpasqualealvarez467
 

Ähnlich wie Oracle SQL Analytic Functions Explained (20)

dplyr Package in R
dplyr Package in Rdplyr Package in R
dplyr Package in R
 
Company segmentation - an approach with R
Company segmentation - an approach with RCompany segmentation - an approach with R
Company segmentation - an approach with R
 
Enabling Applications with Informix' new OLAP functionality
 Enabling Applications with Informix' new OLAP functionality Enabling Applications with Informix' new OLAP functionality
Enabling Applications with Informix' new OLAP functionality
 
Olap Functions Suport in Informix
Olap Functions Suport in InformixOlap Functions Suport in Informix
Olap Functions Suport in Informix
 
Assumptions: Check yo'self before you wreck yourself
Assumptions: Check yo'self before you wreck yourselfAssumptions: Check yo'self before you wreck yourself
Assumptions: Check yo'self before you wreck yourself
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Adding measures to Calcite SQL
Adding measures to Calcite SQLAdding measures to Calcite SQL
Adding measures to Calcite SQL
 
Procedure rol against retail raw data
Procedure rol against retail raw dataProcedure rol against retail raw data
Procedure rol against retail raw data
 
cost II chapter 1.pptx
cost II chapter 1.pptxcost II chapter 1.pptx
cost II chapter 1.pptx
 
12. Basic SQL Queries (2).pptx
12. Basic SQL Queries  (2).pptx12. Basic SQL Queries  (2).pptx
12. Basic SQL Queries (2).pptx
 
IT301-Datawarehousing (1) and its sub topics.pptx
IT301-Datawarehousing (1) and its sub topics.pptxIT301-Datawarehousing (1) and its sub topics.pptx
IT301-Datawarehousing (1) and its sub topics.pptx
 
Sql queries interview questions
Sql queries interview questionsSql queries interview questions
Sql queries interview questions
 
Data ware housing- Introduction to olap .
Data ware housing- Introduction to  olap .Data ware housing- Introduction to  olap .
Data ware housing- Introduction to olap .
 
Engine90 crawford-decision-making (1)
Engine90 crawford-decision-making (1)Engine90 crawford-decision-making (1)
Engine90 crawford-decision-making (1)
 
Getting Started with MDX 20140625a
Getting Started with MDX 20140625aGetting Started with MDX 20140625a
Getting Started with MDX 20140625a
 
Divide and Be Conquered?
Divide and Be Conquered?Divide and Be Conquered?
Divide and Be Conquered?
 
Ali upload
Ali uploadAli upload
Ali upload
 
I really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdfI really need help with this Assignment Please in C programming not .pdf
I really need help with this Assignment Please in C programming not .pdf
 
breakeven point
breakeven pointbreakeven point
breakeven point
 
DW-lecture2.ppt
DW-lecture2.pptDW-lecture2.ppt
DW-lecture2.ppt
 

Kürzlich hochgeladen

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Kürzlich hochgeladen (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Oracle SQL Analytic Functions Explained

  • 2. Toy Retailer Example create table purchases ( category varchar2( 100 ) not null, year_no number not null, month_no number not null, sales number ); category year_no month_no sales Action Figures 2014 1 $ 3,000 Action Figures 2014 2 $ 1,700 Action Figures 2014 3 $ 1,200 Action Figures 2014 4 $ 1,500 Action Figures 2014 5 $ 2,000 Action Figures 2014 6 $ 2,150 Dolls 2014 1 $ 200 Dolls 2014 2 $ 175 Dolls 2014 3 $ 400 Dolls 2014 4 $ 300 Dolls 2014 5 $ 350 …
  • 3. Aggregate Functions * Function used to group together data resulting in a total for that group *Some examples: * Sum * Count * Max * Min * Use “group by” clause to group rows together * Don’t care to see all the rows that make up the total.
  • 4. Aggregate - Sum select category, month_no, sum( sales ) as sales from purchases group by category, month_no; category month_no sales Action Figures 1 $ 3,000 Dolls 1 $ 200 Plush 1 $ 1,000 Video Games 1 $ 1,000 Action Figures 2 $ 1,700 Dolls 2 $ 175 Plush 2 $ 300 …
  • 5. Analytic Functions * Introduced in Oracle v 8i * Also known as windowing functions * Use “partition by” clause to group rows together * The last set of operations performed in a query, except for the order by clause. * All joins, where, group by, and having clauses are completed before the analytic functions are processed. * Can only appear in the select list or order by clauses.
  • 6. Why Analytic Functions? * Why would you want to use Analytic Functions? *Simplify your code. *Code is easier to maintain and read. *In the long run, type less.  * Can use native joins and sub-queries to get the same results, but why would you, if you had a simplier way to do the same thing?
  • 7. Anatomy of Analytic Functions <analytic function> ( [ arg1, … argn] ) OVER ( [ PARTITION BY expr1 [,…,expn] ] [ ORDER BY expr1 [ , …., expn ] ] <windowing clause> )
  • 8. Analytic - Sum select category, month_no, sales, sum( sales ) over ( partition by category ) as ttl_cat_sales, sum( sales ) over ( ) as ttl_sales from purchases; category month_no sales ttl category sales ttl sales Action Figures 1 $ 3,000 $ 11,550 $ 26,075 Action Figures 2 $ 1,700 $ 11,550 $ 26,075 Action Figures 3 $ 1,200 $ 11,550 $ 26,075 Action Figures 4 $ 1,500 $ 11,550 $ 26,075 Action Figures 5 $ 2,000 $ 11,550 $ 26,075 Action Figures 6 $ 2,150 $ 11,550 $ 26,075 Dolls 1 $ 200 $ 1,825 $ 26,075 Dolls 2 $ 175 $ 1,825 $ 26,075 …
  • 9. Anatomy of Rank, dense_rank, row_number RANK | DENSE_RANK | ROW_NUMBER ( [ arg1, … argn] ) OVER ( [ PARTITION BY expr1 [,…,expn] ] ORDER BY expr1 [ , …., expn ] )
  • 10. Difference between Rank, dense_rank, row_number All * serial number for each row based on some column or expression. Rank * If 2 rows have the same value (N), they receive the same sequential value of N, and the next value N+1 will be skipped and the N+2 value will be given to the next record. Dense_rank * If 2 rows have the same value (N), it does not skip position N+1. Row_number * running serial number to the partition records based on the order by clause.
  • 11. Rank, Dense_rank, Row_number select month_no, category, sales, row_number( ) over ( partition by month_no order by sales desc ) as row_no, rank( ) over ( partition by month_no order by sales desc ) as rank_no, dense_rank( ) over ( partition by month_no order by sales desc ) as dense_rank_no from purchases; month_no category sales row_no rank_no dense_rank_no 1Action Figures $ 3,000 1 1 1 1Plush $ 1,000 2 2 2 1Video Games $ 1,000 3 2 2 1Dolls $ 200 4 4 3 2Action Figures $ 1,700 1 1 1 2Video Games $ 500 2 2 2 2Plush $ 300 3 3 3 2Dolls $ 175 4 4 4 …
  • 12. Anatomy of Ratio_to_report RATIO_TO_REPORT ( [ arg1, … argn] ) OVER ( [ PARTITION BY expr1 [,…,expn] ] ORDER BY expr1 [ , …., expn ] )
  • 13. Ratio_to_report select month_no, category, sales, round( ratio_to_report( sales) over ( partition by month_no ) , 2 ) as ratio from purchases; month_nof category sales ratio 1Action Figures $ 3,000 0.58 1Video Games $ 1,000 0.19 1Plush $ 1,000 0.19 1Dolls $ 200 0.04 2Action Figures $ 1,700 0.64 2Video Games $ 500 0.19 2Plush $ 300 0.11 2Dolls $ 175 0.07 3Video Games $ 1,500 0.43
  • 14. Lag and Lead * Provides access to more than one row of a table at the same time without a self join * Lag – access to data from a prior row. * Lead – access to data from a following row. * Examples: * To compare prior value to current record value * Compare prices of items to see if the item was an increase/decrease
  • 15. Lag/Lead select month_no, category, sales ,lag( sales) over ( partition by category order by month_no) as prior_mth_sales ,lead( sales) over ( partition by category order by month_no) as next_mth_sales from purchases; month_no category sales prior_mth_sales next_mth_sales 1Action Figures $ 3,000 $ 1,700 2Action Figures $ 1,700 $ 3,000 $ 1,200 3Action Figures $ 1,200 $ 1,700 $ 1,500 4Action Figures $ 1,500 $ 1,200 $ 2,000 5Action Figures $ 2,000 $ 1,500 $ 2,150 6Action Figures $ 2,150 $ 2,000 1Dolls $ 200 $ 175 2Dolls $ 175 $ 200 $ 400 3Dolls $ 400 $ 175 $ 300
  • 16. Windowing Clause * Windowing definition is a group of rows defined in the windowing clause. * A sliding window of rows is defined for each row * The window determines the range of rows used to perform the calculations for the current row. * Window sizes can be based on either physical number of rows or a logical interval such as time. * Windowing clause examples: * UNBOUNDED PRECEDING : The window starts at the first row of the partition. Only available for start points. * UNBOUNDED FOLLOWING : The window ends at the last row of the partition. Only available for end points. * CURRENT ROW : The window starts or ends at the current row. Can be used as start or end point.
  • 17. Anatomy of Windowing <windowing_function_name > ( [ arg1, … argn] ) OVER ( [ PARTITION BY expr1 [,…,expn] ] ORDER BY expr1 [ , …., expn ] <windowing_clause> )
  • 18. Rolling Totals select month_no, category, sales ,sum( sales) over ( partition by category order by month_no rows unbounded preceding ) as rolling_ttl from purchases; month_no category sales rolling_ttl 1Action Figures $ 3,000 $ 3,000 2Action Figures $ 1,700 $ 4,700 3Action Figures $ 1,200 $ 5,900 4Action Figures $ 1,500 $ 7,400 5Action Figures $ 2,000 $ 9,400 6Action Figures $ 2,150 $ 11,550 1Dolls $ 200 $ 200 2Dolls $ 175 $ 375