DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to calculate median for a data set?

Execute the following SQL Server T-SQL script in SSMS Query Editor to demonstrate the calculation of statistical median. For an odd number set, it produces unique value. For even number set, one has to decide.

-- SQL Server statistical calculation - median - median is different from average

USE AdventureWorks2008;
 
WITH cteOrderQty
     AS (SELECT DISTINCT OrderQty
         FROM   Sales.SalesOrderDetail)
SELECT   MedianOrderQty = a.OrderQty
FROM     cteOrderQty a
         CROSS JOIN cteOrderQty b
GROUP BY a.OrderQty
HAVING   SUM(CASE
               WHEN b.OrderQty <= a.OrderQty THEN 1
               ELSE 0
             END) >= (COUNT(* )) / 2
         AND SUM(CASE
                   WHEN b.OrderQty >= a.OrderQty THEN 1
                   ELSE 0
                 END) >= (COUNT(* ) / 2)
/*
MedianOrderQty
21
22
20

*/

 

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE