SlideShare una empresa de Scribd logo
1 de 28
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Web Design Notes
Web Design NotesWeb Design Notes
Web Design Notes
 
HTML Basics by software development company india
HTML Basics by software development company indiaHTML Basics by software development company india
HTML Basics by software development company india
 
Basic Html Knowledge for students
Basic Html Knowledge for studentsBasic Html Knowledge for students
Basic Html Knowledge for students
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
HTML
HTMLHTML
HTML
 
Php ppt
Php pptPhp ppt
Php ppt
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Web Development using HTML & CSS
Web Development using HTML & CSSWeb Development using HTML & CSS
Web Development using HTML & CSS
 
Presentation on HTML
Presentation on HTMLPresentation on HTML
Presentation on HTML
 
Ielts (listening section)
Ielts (listening section)Ielts (listening section)
Ielts (listening section)
 
Xml
XmlXml
Xml
 
Html ppt
Html pptHtml ppt
Html ppt
 
Teaching reading
Teaching readingTeaching reading
Teaching reading
 
Overview PTE Academic Practice Test
Overview PTE Academic Practice Test Overview PTE Academic Practice Test
Overview PTE Academic Practice Test
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Intro to html 5
Intro to html 5Intro to html 5
Intro to html 5
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
 
Final presentation on python
Final presentation on pythonFinal presentation on python
Final presentation on python
 
Html basics
Html basicsHtml basics
Html basics
 

Similar a 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 developersLucas 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 TalligramJolieto Cambalo Caparida
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming hccit
 
Oracle_Analytical_function.pdf
Oracle_Analytical_function.pdfOracle_Analytical_function.pdf
Oracle_Analytical_function.pdfKalyankumarVenkat1
 
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.docxcockekeshia
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONArun 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 .docxjasoninnes20
 
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 .docxcurwenmichaela
 
SQL Commands Part 1.pptx
SQL Commands Part 1.pptxSQL Commands Part 1.pptx
SQL Commands Part 1.pptxRUBAB79
 
3.4 Measures of Position
3.4 Measures of Position3.4 Measures of Position
3.4 Measures of Positionmlong24
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Techglyphs
 
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
 

Similar a 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
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
[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
 
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
 
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
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
[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
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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