SlideShare a Scribd company logo
Median SQL Programming Median query – How to calculate the median Parts Median
Notes on Median Slides These slides will be part of our upcoming intermediate and/or perhaps advanced SQL queries course. The basic concept of using TOP was found on a tek-tips SQL forum. At this time we are using Chris Date’s famous parts table. We will add versions for the bookstore database as well. This script has been tested with SQL Server only at this time. Parts Median
Contact Information Parts Median P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com [email_address]   Copyright 2001-2011. All rights reserved.
Median Resources SQL scripts will be found on box.net at http://tinyurl.com/SQLScripts   Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases   Follow up questions? [email_address]   Parts Median
Assumptions It is assumed the student is familiar with how to create a database and how to put it in use if required. These statements are not covered in these slides. Parts Median
Business Case SQL has a function AVG which will take the average or arithmetic mean. It does not have one for the median. These slides will show how to calculate the median of a dataset. The median is the value in a series above which lie 50% of the values and below which lie the other 50%. If there are an even number of values in the series it is the average of the two innermost above values. The median has many uses. One common use is in real estate where the median may give us a better feel for the typical prices paid. Parts Median
Approach We will calculate the median by using an SQL select of the top 50 percent of a dataset. This will be done twice. Once to obtain the record 50% of the way down from the top and again to find the record 50% of the way up from the bottom. If there are an odd number (including 1) of records the same row will be retrieved twice which is fine. We will then average the two values returned. Parts Median
Create Table We will use Chris Date’s famous parts table. Parts Median CREATE TABLE Parts  (part_nbr VARCHAR(5) NOT NULL PRIMARY KEY , part_name VARCHAR(50) NOT NULL , part_color VARCHAR(50) NOT NULL  , part_wgt INTEGER NOT NULL  , city_name VARCHAR(50) NOT NULL );
Load Data Load the following data and/or experiment with your own values… Parts Median INSERT INTO Parts (part_nbr, part_name, part_color, part_wgt, city_name) VALUES ('p1', 'Nut', 'Red', 12, 'London') , ('p2', 'Bolt', 'Green', 17, 'Paris') , ('p3', 'Cam', 'Blue', 12, 'Paris') , ('p4', 'Screw', 'Red', 14, 'London') , ('p5', 'Cam', 'Blue', 12, 'Paris') , ('p6', 'Cog', 'Red', 19, 'London') ;
Calculate the median Union the result of the two select tops. Then average the two results. Parts Median select avg(wgt) as median from (select max(part_wgt) as wgt From (select top 50 percent * from parts order by part_wgt asc) a union select min(part_wgt) from (select top 50 percent * from parts order by part_wgt desc) d) u;
Results Parts Median
Explanation Use a subquery to select the top 50 percent of the dataset in ascending order.  Use a named outer query (table expression) to select the bottom value from this list. Assign a column alias to the max(value). Use a subquery to select the bottom 50 percent of the dataset in descending order.  Use a named outer query (table expression) to select the top value from this list. Union the result of the two named queries into another named query . Select from this named query. Average the values in the union and assign a new column alias of median. Parts Median

More Related Content

PPTX
DBMS-Quick Reference
TXT
Readme do not_touch_files
PPT
Neon Something Different
PPT
Allemand
PDF
How to Do Lean Planning (and what does that mean anyway)
PDF
ifilms Company Profile
PPT
Buildings Architecture 3 D Designs Wallpapers
DBMS-Quick Reference
Readme do not_touch_files
Neon Something Different
Allemand
How to Do Lean Planning (and what does that mean anyway)
ifilms Company Profile
Buildings Architecture 3 D Designs Wallpapers

Viewers also liked (14)

PPS
Photos With Reflections
PDF
From Neo to Trinity: The Matrix Reinvented
PDF
All About Gold
PPT
Being Caught Stealing (Con La Mano En El Pastel)
PDF
Cloud Computing Sun Microsystems
PPT
Samantha Resume
PDF
Tamkeen capital investment model 2013
PPS
one woman satisfies 12 men
PPT
Rockets
PPS
Lips & Mouth
PPT
Hurricanes & Tornados
PDF
Social enter strategic planning
PDF
AmauryABG_CV
PPT
Lean Fables from Adland
Photos With Reflections
From Neo to Trinity: The Matrix Reinvented
All About Gold
Being Caught Stealing (Con La Mano En El Pastel)
Cloud Computing Sun Microsystems
Samantha Resume
Tamkeen capital investment model 2013
one woman satisfies 12 men
Rockets
Lips & Mouth
Hurricanes & Tornados
Social enter strategic planning
AmauryABG_CV
Lean Fables from Adland
Ad

Similar to SQL206 SQL Median (20)

PDF
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
PPT
Review of SQL
PDF
MODULE 1.pdf foundations of data science for final
PDF
Sql wksht-3
PPT
Informix partitioning interval_rolling_window_table
PDF
Advanced SQL For Data Scientists
PPTX
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
PPT
Sql server introduction to sql server
PPTX
MS Access Ch 2 PPT
PPT
James Colby Maddox Business Intellignece and Computer Science Portfolio
PPT
Mssql
DOCX
SQL report
PDF
Ugif 10 2012 ppt0000002
PPT
Olap Functions Suport in Informix
PPTX
Mean vs Median
PDF
Microsoft SQL Server Filtered Indexes & Sparse Columns Feb 2011
PDF
Using grouping sets in sql server 2008 tech republic
PDF
The ultimate-guide-to-sql
PDF
Sql Server Statistics
PPT
MS SQL Server.ppt
advance-sqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal.pdf
Review of SQL
MODULE 1.pdf foundations of data science for final
Sql wksht-3
Informix partitioning interval_rolling_window_table
Advanced SQL For Data Scientists
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Sql server introduction to sql server
MS Access Ch 2 PPT
James Colby Maddox Business Intellignece and Computer Science Portfolio
Mssql
SQL report
Ugif 10 2012 ppt0000002
Olap Functions Suport in Informix
Mean vs Median
Microsoft SQL Server Filtered Indexes & Sparse Columns Feb 2011
Using grouping sets in sql server 2008 tech republic
The ultimate-guide-to-sql
Sql Server Statistics
MS SQL Server.ppt
Ad

More from Dan D'Urso (20)

PPT
SQL201S Accelerated Introduction to MySQL Queries
PPT
LCD201d Database Diagramming with Lucidchart
PPTX
Database Normalization
PPT
VIS201d Visio Database Diagramming
PPT
PRJ101a Project 2013 Accelerated
PPT
PRJ101xl Project Libre Basic Training
PPT
Introduction to coding using Python
PPTX
Stem conference
PDF
SQL200A Microsoft Access SQL Design
PPTX
Microsoft access self joins
PDF
SQL302 Intermediate SQL
PDF
AIN106 Access Reporting and Analysis
PPT
SQL302 Intermediate SQL Workshop 3
PPT
SQL302 Intermediate SQL Workshop 2
PDF
Course Catalog
PPT
SQL302 Intermediate SQL Workshop 1
PDF
SQL212 Oracle SQL Manual
PDF
SQL201W MySQL SQL Manual
PDF
AIN100
PPT
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3
SQL201S Accelerated Introduction to MySQL Queries
LCD201d Database Diagramming with Lucidchart
Database Normalization
VIS201d Visio Database Diagramming
PRJ101a Project 2013 Accelerated
PRJ101xl Project Libre Basic Training
Introduction to coding using Python
Stem conference
SQL200A Microsoft Access SQL Design
Microsoft access self joins
SQL302 Intermediate SQL
AIN106 Access Reporting and Analysis
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 2
Course Catalog
SQL302 Intermediate SQL Workshop 1
SQL212 Oracle SQL Manual
SQL201W MySQL SQL Manual
AIN100
SQL202.3 Accelerated Introduction to SQL Using SQL Server Module 3

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation theory and applications.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Machine Learning_overview_presentation.pptx
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
cuic standard and advanced reporting.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
Electronic commerce courselecture one. Pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectral efficient network and resource selection model in 5G networks
Machine Learning_overview_presentation.pptx
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Network Security Unit 5.pdf for BCA BBA.
cuic standard and advanced reporting.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
NewMind AI Weekly Chronicles - August'25-Week II
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing

SQL206 SQL Median

  • 1. Median SQL Programming Median query – How to calculate the median Parts Median
  • 2. Notes on Median Slides These slides will be part of our upcoming intermediate and/or perhaps advanced SQL queries course. The basic concept of using TOP was found on a tek-tips SQL forum. At this time we are using Chris Date’s famous parts table. We will add versions for the bookstore database as well. This script has been tested with SQL Server only at this time. Parts Median
  • 3. Contact Information Parts Median P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com [email_address] Copyright 2001-2011. All rights reserved.
  • 4. Median Resources SQL scripts will be found on box.net at http://tinyurl.com/SQLScripts Slides can be viewed on SlideShare… http://www.slideshare.net/OCDatabases Follow up questions? [email_address] Parts Median
  • 5. Assumptions It is assumed the student is familiar with how to create a database and how to put it in use if required. These statements are not covered in these slides. Parts Median
  • 6. Business Case SQL has a function AVG which will take the average or arithmetic mean. It does not have one for the median. These slides will show how to calculate the median of a dataset. The median is the value in a series above which lie 50% of the values and below which lie the other 50%. If there are an even number of values in the series it is the average of the two innermost above values. The median has many uses. One common use is in real estate where the median may give us a better feel for the typical prices paid. Parts Median
  • 7. Approach We will calculate the median by using an SQL select of the top 50 percent of a dataset. This will be done twice. Once to obtain the record 50% of the way down from the top and again to find the record 50% of the way up from the bottom. If there are an odd number (including 1) of records the same row will be retrieved twice which is fine. We will then average the two values returned. Parts Median
  • 8. Create Table We will use Chris Date’s famous parts table. Parts Median CREATE TABLE Parts (part_nbr VARCHAR(5) NOT NULL PRIMARY KEY , part_name VARCHAR(50) NOT NULL , part_color VARCHAR(50) NOT NULL , part_wgt INTEGER NOT NULL , city_name VARCHAR(50) NOT NULL );
  • 9. Load Data Load the following data and/or experiment with your own values… Parts Median INSERT INTO Parts (part_nbr, part_name, part_color, part_wgt, city_name) VALUES ('p1', 'Nut', 'Red', 12, 'London') , ('p2', 'Bolt', 'Green', 17, 'Paris') , ('p3', 'Cam', 'Blue', 12, 'Paris') , ('p4', 'Screw', 'Red', 14, 'London') , ('p5', 'Cam', 'Blue', 12, 'Paris') , ('p6', 'Cog', 'Red', 19, 'London') ;
  • 10. Calculate the median Union the result of the two select tops. Then average the two results. Parts Median select avg(wgt) as median from (select max(part_wgt) as wgt From (select top 50 percent * from parts order by part_wgt asc) a union select min(part_wgt) from (select top 50 percent * from parts order by part_wgt desc) d) u;
  • 12. Explanation Use a subquery to select the top 50 percent of the dataset in ascending order. Use a named outer query (table expression) to select the bottom value from this list. Assign a column alias to the max(value). Use a subquery to select the bottom 50 percent of the dataset in descending order. Use a named outer query (table expression) to select the top value from this list. Union the result of the two named queries into another named query . Select from this named query. Average the values in the union and assign a new column alias of median. Parts Median