SlideShare a Scribd company logo
Presented by Steve Stedman and Aaron Buma
Welcome
 Welcome to all those joining us remotely.
 For any questions via Google On Air Broadcasts, we will
address these at the end of the training
 Training provided by Emergency Reporting
 http://EmergencyReporting.com
 Presented by Steve Stedman
 And Aaron Buma
Agenda
 TOP(N)
 RANK and DENSE_RANK
 ROW_NUMBER
 NTILE
 OVER clause enhancements
 LAG and LEAD, FIRST_VALUE and LAST_VALUE
 PERCENT_RANK
 PERCENTILE_DISC and PERCENTILE_CONT
 CUME_DIST - Cumulative Distribution
Presented by Aaron Buma
Part One – Aaron Buma
 TOP (n)
 WITH TIES
 PERCENT
 RANK and DENSE_RANK
 ROW_NUMBER
SELECT TOP (N)
 TOP (n)
 n as variable
 WITH TIES
 PERCENT
Rank, Dense_Rank, Row_number
 RANK and DENSE_RANK
 Requires “ OVER(ORDER BY columnName ASC/DESC)
to declare what to rank and in what order
 Identical results until duplicates are encountered
 ROW_NUMBER
 Disregards duplicates
Presented by Steve Stedman
Part Two – Steve Stedman
 NTILE
 OVER Clause Enhancements
 ROWS PRECEDING, FOLLOWING, UNBOUNDED
 RANGE PRECEDING, FOLLOWING, UNBOUNDED
 LAG and LEAD
 FIRST_VALUE and LAST_VALUE
 PERCENT_RANK
 PERCENTILE_DISC and PERCENTILE_CONT
 CUME_DIST - Cumulative Distribution
NTILE
 Median – Split the group into 2 evenly sized groups.
 Evenly in this case is defined as being as close to even as
possible given the number of items in the group.
 Quartile – Split the set into 4 evenly sized groups.
 Decile – Split the set into 10 evenly sized groups.
 Percentile – Split the group into 100 evenly sized groups.
 NTile – Split the group into N evenly sized groups.
The Pre-2012 OVER Clause
 The OVER clause before SQL Server 2012…
 Really handy to perform aggregates over a different
range than your standard grouping.
OVER Clause Enhancements
 ROWS PRECEDING, FOLLOWING, UNBOUNDED
 Rows refers to the current row and those before or after
base on preceding or following.
 RANGE PRECEDING, FOLLOWING, UNBOUNDED
 Range means all values in the current range and those
before or after.
PRECEDING, FOLLOWING,
UNBOUNDED
 ROWS or RANGE- specifying rows or range
 PRECEDING – get rows before the current one
 FOLLOWING – get rows after the current one
 UNBOUNDED – get all before or after
 CURRENT ROW
Demo
--ROWS PRECEDING
-- http://stevestedman.com/?p=1454
-- look at the sum of revenue over a trailing 3 year period
select Year, DepartmentID, Revenue,
sum(Revenue) OVER (PARTITION by DepartmentID
ORDER BY [YEAR]
ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as Prev3
from REVENUE order by departmentID, year;
--ROWS PRECEDING
select Year, DepartmentID, Revenue,
sum(Revenue) OVER (PARTITION by DepartmentID
ORDER BY [YEAR]
ROWS BETWEEN 5 PRECEDING AND 2 PRECEDING) as Prev5to3
from REVENUE order by departmentID, year;
-- ROWS FOLLOWING
-- http://stevestedman.com/?p=1454
select Year, DepartmentID, Revenue,
sum(Revenue) OVER (PARTITION by DepartmentID
ORDER BY [YEAR]
ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING) as Next3
from REVENUE order by departmentID, year;
--ROWS PRECEDING
select Year, DepartmentID, Revenue,
sum(Revenue) OVER (PARTITION by DepartmentID
ORDER BY [YEAR]
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as BeforeAndAfter
from REVENUE order by departmentID, year;
LAG and LEAD
 Allows you to reference a value in a row before or a row
after the current row
 Over clause is used to specify the ordering and
partitioning
FIRST_VALUEand LAST_VALUE
 FIRST_VALUE returns the first value in an ordered set of
values and
 LAST_VALUE returns the last value in an ordered set of
values
 Utilize the OVER clause to set ranges and orders
 Interesting catch – LAST_VALUE specifies the last value so
far unless you specify otherwise
PERCENT_RANK
 PERCENT_RANK is defined as the number of values
that are the same or less than the current value divided
by one less than the number of values
 Different from PERCENTILE
PERCENTILE_DISC and
PERCENTILE_CONT
 PERCENTILE_CONT interpolates the appropriate value,
even if it is not in the set.
 PERCENTILE_DISC picks a percentile that exists in the set.
 Keep in mind that any nulls in the data set are ignored.
 What’s the difference in the names
 CONT stands for continuous
 DISC stands for discrete distribution which means that the
percentile will exist in the set.
CUME_DIST - Cumulative
Distribution
 CUME_DIST is the function that maps values to their
percentile rank in a distribution.
 The CUME_DIST function calculates the possibility of
another occurrence being of that value or lesser than
that among a group of values.
More statistics with Cumulative
Distribution
 Testing the Rand() function
 Testing probability with dice rolls
Quiz 1:
 Which of the following is incorrect:
 In regards to: TOP (n) PERCENT
 n can be any value
 n can be any value from 0 – 100
 n can be a variable, valued 0 - 100
Quiz 2:
 If a table with four values of ‘1’ and a single ‘2’ in ColumnA,
what will the result set be with the following statement:
Quiz 3
 If a duplicate value is encountered, ROW_NUMBER does
which of the following:
 Repeat the counter/row number until the first non-duplicate
is found, the continue with next number
 Continue to increase the counter/row number when a
duplicate is found
 Repeat the counter/row number until the first non-duplicate
is found, then skip to number which would match the row
number as if no duplicates were encountered.
Quiz 4:
 NTILE(100) is also known as?
 Centile
 Percentile
 Tile100
 Decile
Quiz 5:
 The query fragment above uses up to how many rows
in the AVG calculation?
 All rows
 2 rows
 3 rows
Any Questions?
 TOP(N)
 RANK and DENSE_RANK
 ROW_NUMBER
 NTILE
 OVER clause enhancements
 LAG and LEAD, FIRST_VALUE and LAST_VALUE
 PERCENT_RANK
 PERCENTILE_DISC and PERCENTILE_CONT
 CUME_DIST - Cumulative Distribution
For More Information
 Visit http://EmergencyReporting.com to find out more
about Emergency Reporting.
 Aaron on the web
 http://AaronBuma.com
 Twitter: @AaronDBuma
 Steve on the web
 http://SteveStedman.com
 twitter: @SqlEmt
Tune in next week
 Thursday 2/12 at 9:00am (pacific time).
 Topics
 Set Operators
 UNION, UNION ALL, INTERSECT, EXCEPT
 Set Grouping

More Related Content

What's hot

SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
Smriti Jain
 
Sql task
Sql taskSql task
Sql task
Nawaz Sk
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
Raveena Thakur
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
Ankit Rai
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
Priyabrat Kar
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
Janki Shah
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
Dhananjay Goel
 
PLSQL tutorial...
PLSQL tutorial...PLSQL tutorial...
PLSQL tutorial...
JYOTI RANJAN PAL
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
valuebound
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
vijaybusu
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
Prashant Saini
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
oysteing
 
Triggers
TriggersTriggers
Triggers
Pooja Dixit
 
Sql query [select, sub] 4
Sql query [select, sub] 4Sql query [select, sub] 4
Sql query [select, sub] 4
Dr. C.V. Suresh Babu
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
Lakshman Basnet
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
Bharat Kalia
 
8. transactions
8. transactions8. transactions
8. transactions
Amrit Kaur
 
Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)
Jargalsaikhan Alyeksandr
 

What's hot (20)

SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
Sql task
Sql taskSql task
Sql task
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
PLSQL tutorial...
PLSQL tutorial...PLSQL tutorial...
PLSQL tutorial...
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
 
MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions MySQL 8.0: Common Table Expressions
MySQL 8.0: Common Table Expressions
 
Triggers
TriggersTriggers
Triggers
 
Sql query [select, sub] 4
Sql query [select, sub] 4Sql query [select, sub] 4
Sql query [select, sub] 4
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
8. transactions
8. transactions8. transactions
8. transactions
 
Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)Database design & Normalization (1NF, 2NF, 3NF)
Database design & Normalization (1NF, 2NF, 3NF)
 

Similar to SQL Server TOP(), Ranking, NTILE, and Aggregate Functions

Introduction Oracle Database 11g Release 2 for developers
Introduction Oracle Database 11g Release 2 for developersIntroduction Oracle Database 11g Release 2 for developers
Introduction Oracle Database 11g Release 2 for developers
Lucas Jellema
 
Organzation of scores, Uses of a Talligram
Organzation of scores, Uses of a TalligramOrganzation of scores, Uses of a Talligram
Organzation of scores, Uses of a Talligram
Jolieto Cambalo Caparida
 
Sampling Data in T-SQL
Sampling Data in T-SQLSampling Data in T-SQL
Sampling Data in T-SQL
Tim Mills-Groninger
 
SQL
SQLSQL
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
Nitesh Singh
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
hccit
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
अभिषेक शर्मा
 
Data integrity
Data integrityData integrity
Data integrity
Rahul Gupta
 
Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdf
KalyankumarVenkat1
 
Week 4 Lecture 12 Significance Earlier we discussed co.docx
Week 4 Lecture 12 Significance Earlier we discussed co.docxWeek 4 Lecture 12 Significance Earlier we discussed co.docx
Week 4 Lecture 12 Significance Earlier we discussed co.docx
cockekeshia
 
LECTURE NO 7.pdf
LECTURE NO 7.pdfLECTURE NO 7.pdf
LECTURE NO 7.pdf
WraArirmiwni
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docxBUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
jasoninnes20
 
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docxBUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
curwenmichaela
 
Ch08
Ch08Ch08
SQL Commands Part 1.pptx
SQL Commands Part 1.pptxSQL Commands Part 1.pptx
SQL Commands Part 1.pptx
RUBAB79
 
3.4 Measures of Position
3.4 Measures of Position3.4 Measures of Position
3.4 Measures of Position
mlong24
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
Techglyphs
 
SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)
Logan Palanisamy
 
Stored procedures
Stored proceduresStored procedures

Similar to SQL Server TOP(), Ranking, NTILE, and Aggregate Functions (20)

Introduction Oracle Database 11g Release 2 for developers
Introduction Oracle Database 11g Release 2 for developersIntroduction Oracle Database 11g Release 2 for developers
Introduction Oracle Database 11g Release 2 for developers
 
Organzation of scores, Uses of a Talligram
Organzation of scores, Uses of a TalligramOrganzation of scores, Uses of a Talligram
Organzation of scores, Uses of a Talligram
 
Sampling Data in T-SQL
Sampling Data in T-SQLSampling Data in T-SQL
Sampling Data in T-SQL
 
SQL
SQLSQL
SQL
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
Data integrity
Data integrityData integrity
Data integrity
 
Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdf
 
Week 4 Lecture 12 Significance Earlier we discussed co.docx
Week 4 Lecture 12 Significance Earlier we discussed co.docxWeek 4 Lecture 12 Significance Earlier we discussed co.docx
Week 4 Lecture 12 Significance Earlier we discussed co.docx
 
LECTURE NO 7.pdf
LECTURE NO 7.pdfLECTURE NO 7.pdf
LECTURE NO 7.pdf
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docxBUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
 
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docxBUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
BUS 308 Week 3 Lecture 3 Setting up ANOVA and Chi Square .docx
 
Ch08
Ch08Ch08
Ch08
 
SQL Commands Part 1.pptx
SQL Commands Part 1.pptxSQL Commands Part 1.pptx
SQL Commands Part 1.pptx
 
3.4 Measures of Position
3.4 Measures of Position3.4 Measures of Position
3.4 Measures of Position
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)SQL for pattern matching (Oracle 12c)
SQL for pattern matching (Oracle 12c)
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 

Recently uploaded

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 

Recently uploaded (20)

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 

SQL Server TOP(), Ranking, NTILE, and Aggregate Functions

  • 1. Presented by Steve Stedman and Aaron Buma
  • 2. Welcome  Welcome to all those joining us remotely.  For any questions via Google On Air Broadcasts, we will address these at the end of the training  Training provided by Emergency Reporting  http://EmergencyReporting.com  Presented by Steve Stedman  And Aaron Buma
  • 3. Agenda  TOP(N)  RANK and DENSE_RANK  ROW_NUMBER  NTILE  OVER clause enhancements  LAG and LEAD, FIRST_VALUE and LAST_VALUE  PERCENT_RANK  PERCENTILE_DISC and PERCENTILE_CONT  CUME_DIST - Cumulative Distribution
  • 5. Part One – Aaron Buma  TOP (n)  WITH TIES  PERCENT  RANK and DENSE_RANK  ROW_NUMBER
  • 6. SELECT TOP (N)  TOP (n)  n as variable  WITH TIES  PERCENT
  • 7. Rank, Dense_Rank, Row_number  RANK and DENSE_RANK  Requires “ OVER(ORDER BY columnName ASC/DESC) to declare what to rank and in what order  Identical results until duplicates are encountered  ROW_NUMBER  Disregards duplicates
  • 9. Part Two – Steve Stedman  NTILE  OVER Clause Enhancements  ROWS PRECEDING, FOLLOWING, UNBOUNDED  RANGE PRECEDING, FOLLOWING, UNBOUNDED  LAG and LEAD  FIRST_VALUE and LAST_VALUE  PERCENT_RANK  PERCENTILE_DISC and PERCENTILE_CONT  CUME_DIST - Cumulative Distribution
  • 10. NTILE  Median – Split the group into 2 evenly sized groups.  Evenly in this case is defined as being as close to even as possible given the number of items in the group.  Quartile – Split the set into 4 evenly sized groups.  Decile – Split the set into 10 evenly sized groups.  Percentile – Split the group into 100 evenly sized groups.  NTile – Split the group into N evenly sized groups.
  • 11. The Pre-2012 OVER Clause  The OVER clause before SQL Server 2012…  Really handy to perform aggregates over a different range than your standard grouping.
  • 12. OVER Clause Enhancements  ROWS PRECEDING, FOLLOWING, UNBOUNDED  Rows refers to the current row and those before or after base on preceding or following.  RANGE PRECEDING, FOLLOWING, UNBOUNDED  Range means all values in the current range and those before or after.
  • 13. PRECEDING, FOLLOWING, UNBOUNDED  ROWS or RANGE- specifying rows or range  PRECEDING – get rows before the current one  FOLLOWING – get rows after the current one  UNBOUNDED – get all before or after  CURRENT ROW
  • 14. Demo --ROWS PRECEDING -- http://stevestedman.com/?p=1454 -- look at the sum of revenue over a trailing 3 year period select Year, DepartmentID, Revenue, sum(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) as Prev3 from REVENUE order by departmentID, year; --ROWS PRECEDING select Year, DepartmentID, Revenue, sum(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS BETWEEN 5 PRECEDING AND 2 PRECEDING) as Prev5to3 from REVENUE order by departmentID, year; -- ROWS FOLLOWING -- http://stevestedman.com/?p=1454 select Year, DepartmentID, Revenue, sum(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING) as Next3 from REVENUE order by departmentID, year; --ROWS PRECEDING select Year, DepartmentID, Revenue, sum(Revenue) OVER (PARTITION by DepartmentID ORDER BY [YEAR] ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) as BeforeAndAfter from REVENUE order by departmentID, year;
  • 15. LAG and LEAD  Allows you to reference a value in a row before or a row after the current row  Over clause is used to specify the ordering and partitioning
  • 16. FIRST_VALUEand LAST_VALUE  FIRST_VALUE returns the first value in an ordered set of values and  LAST_VALUE returns the last value in an ordered set of values  Utilize the OVER clause to set ranges and orders  Interesting catch – LAST_VALUE specifies the last value so far unless you specify otherwise
  • 17. PERCENT_RANK  PERCENT_RANK is defined as the number of values that are the same or less than the current value divided by one less than the number of values  Different from PERCENTILE
  • 18. PERCENTILE_DISC and PERCENTILE_CONT  PERCENTILE_CONT interpolates the appropriate value, even if it is not in the set.  PERCENTILE_DISC picks a percentile that exists in the set.  Keep in mind that any nulls in the data set are ignored.  What’s the difference in the names  CONT stands for continuous  DISC stands for discrete distribution which means that the percentile will exist in the set.
  • 19. CUME_DIST - Cumulative Distribution  CUME_DIST is the function that maps values to their percentile rank in a distribution.  The CUME_DIST function calculates the possibility of another occurrence being of that value or lesser than that among a group of values.
  • 20. More statistics with Cumulative Distribution  Testing the Rand() function  Testing probability with dice rolls
  • 21. Quiz 1:  Which of the following is incorrect:  In regards to: TOP (n) PERCENT  n can be any value  n can be any value from 0 – 100  n can be a variable, valued 0 - 100
  • 22. Quiz 2:  If a table with four values of ‘1’ and a single ‘2’ in ColumnA, what will the result set be with the following statement:
  • 23. Quiz 3  If a duplicate value is encountered, ROW_NUMBER does which of the following:  Repeat the counter/row number until the first non-duplicate is found, the continue with next number  Continue to increase the counter/row number when a duplicate is found  Repeat the counter/row number until the first non-duplicate is found, then skip to number which would match the row number as if no duplicates were encountered.
  • 24. Quiz 4:  NTILE(100) is also known as?  Centile  Percentile  Tile100  Decile
  • 25. Quiz 5:  The query fragment above uses up to how many rows in the AVG calculation?  All rows  2 rows  3 rows
  • 26. Any Questions?  TOP(N)  RANK and DENSE_RANK  ROW_NUMBER  NTILE  OVER clause enhancements  LAG and LEAD, FIRST_VALUE and LAST_VALUE  PERCENT_RANK  PERCENTILE_DISC and PERCENTILE_CONT  CUME_DIST - Cumulative Distribution
  • 27. For More Information  Visit http://EmergencyReporting.com to find out more about Emergency Reporting.  Aaron on the web  http://AaronBuma.com  Twitter: @AaronDBuma  Steve on the web  http://SteveStedman.com  twitter: @SqlEmt
  • 28. Tune in next week  Thursday 2/12 at 9:00am (pacific time).  Topics  Set Operators  UNION, UNION ALL, INTERSECT, EXCEPT  Set Grouping