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)

PPTX
Mysql
PPT
NLP Natural Language Processing 10th Chapter.ppt
ODP
Introducing Modern Perl
PPT
PPTX
SQL Server - Introduction to TSQL
ODP
DrupalCon Chicago Practical MongoDB and Drupal
PPT
P H P Part I I, By Kian
PPT
Open Source Package Php Mysql 1228203701094763 9
PPT
Open Source Package PHP & MySQL
PPT
Introduction to Assembly Language
ODP
Introduction to Perl - Day 2
PPTX
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
PPT
Php Data Objects
PPT
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
PPT
ORACLE PL SQL
ODP
Into to DBI with DBD::Oracle
PPT
Dealing with Legacy Perl Code - Peter Scott
PDF
Quick start learn dax basics in 30 minutes
ODP
Intermediate Perl
PDF
Mysql
NLP Natural Language Processing 10th Chapter.ppt
Introducing Modern Perl
SQL Server - Introduction to TSQL
DrupalCon Chicago Practical MongoDB and Drupal
P H P Part I I, By Kian
Open Source Package Php Mysql 1228203701094763 9
Open Source Package PHP & MySQL
Introduction to Assembly Language
Introduction to Perl - Day 2
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
Php Data Objects
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
ORACLE PL SQL
Into to DBI with DBD::Oracle
Dealing with Legacy Perl Code - Peter Scott
Quick start learn dax basics in 30 minutes
Intermediate Perl
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)

PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Machine learning based COVID-19 study performance prediction
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Encapsulation theory and applications.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
A comparative analysis of optical character recognition models for extracting...
Machine learning based COVID-19 study performance prediction
MIND Revenue Release Quarter 2 2025 Press Release
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The AUB Centre for AI in Media Proposal.docx
Advanced methodologies resolving dimensionality complications for autism neur...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Network Security Unit 5.pdf for BCA BBA.
Assigned Numbers - 2025 - Bluetooth® Document
Encapsulation theory and applications.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Digital-Transformation-Roadmap-for-Companies.pptx

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