SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Effective T-SQL for Median


Effective T-SQL for Median

Author
Message
dkschill
dkschill
Mr or Mrs. 500
Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)

Group: General Forum Members
Points: 587 Visits: 430
Is this an effective way to find median?


CREATE TABLE #T (i TINYINT);

GO

INSERT INTO #T
SELECT ABS(CHECKSUM(NEWID())) % 250

GO 1000

;WITH t AS (SELECT i, ROW_NUMBER() OVER (ORDER BY i) AS n, count(*) OVER (PARTITION BY (SELECT NULL)) AS c FROM #T)
SELECT
AVG(i) AS Median
FROM t
WHERE
( c % 2 = 1 AND n = ((c-1)/2)+1 )
OR (c % 2 = 0 AND (n = c / 2 OR n = c / 2 + 1))


Luis Cazares
Luis Cazares
SSCoach
SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)SSCoach (16K reputation)

Group: General Forum Members
Points: 16553 Visits: 19095
Last week I came up with this option. I haven't made performace tests. Maybe you could help me with that.


DECLARE @test TABLE(
myint int)
INSERT INTO @test VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9);

WITH CTE AS(
SELECT myint,
NTILE( 2) OVER( ORDER BY myint) tile
FROM @test
)
SELECT CASE WHEN SUM( CASE WHEN tile = 1 THEN 1 END) = SUM( CASE WHEN tile = 2 THEN 1 END)
THEN (MAX( CASE WHEN tile = 1 THEN myint END) + MIN( CASE WHEN tile = 2 THEN myint END))/2.0
ELSE MAX( CASE WHEN tile = 1 THEN myint END) END
FROM CTE




Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?


How to post data/code on a forum to get the best help: Option 1 / Option 2
TheSQLGuru
TheSQLGuru
SSChampion
SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)SSChampion (12K reputation)

Group: General Forum Members
Points: 12451 Visits: 8552
Fortunately for you SQL 2012 has much better Windowing Function support. Look into the PERCENTILE_CONT function. I also HIGHLY recommend you purchase Itzik Ben-Gan's SQL Server 2012 High-Performance TSQL Using Window Functions book.

Best,
Kevin G. Boles
SQL Server Consultant
SQL MVP 2007-2012
TheSQLGuru on googles mail service
dkschill
dkschill
Mr or Mrs. 500
Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)

Group: General Forum Members
Points: 587 Visits: 430
TheSQLGuru (7/30/2013)
Fortunately for you SQL 2012 has much better Windowing Function support. Look into the PERCENTILE_CONT function. I also HIGHLY recommend you purchase Itzik Ben-Gan's SQL Server 2012 High-Performance TSQL Using Window Functions book.


This is awesome thanks!
Alan.B
Alan.B
SSCertifiable
SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)

Group: General Forum Members
Points: 5162 Visits: 7725
dkschill (7/30/2013)
Is this an effective way to find median?


CREATE TABLE #T (i TINYINT);

GO

INSERT INTO #T
SELECT ABS(CHECKSUM(NEWID())) % 250

GO 1000

;WITH t AS (SELECT i, ROW_NUMBER() OVER (ORDER BY i) AS n, count(*) OVER (PARTITION BY (SELECT NULL)) AS c FROM #T)
SELECT
AVG(i) AS Median
FROM t
WHERE
( c % 2 = 1 AND n = ((c-1)/2)+1 )
OR (c % 2 = 0 AND (n = c / 2 OR n = c / 2 + 1))




First and foremost, for your sample data, don't use GO 1000. You will find a tally table works much better for this kind of thing.


WITH t(i) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM sys.all_objects)
INSERT INTO #T
SELECT ABS(CHECKSUM(NEWID()))%200
FROM t
WHERE i<=1000;



My non-2012 solution is:


;WITH t(i,n,c) AS
( SELECT i,
ROW_NUMBER() OVER (ORDER BY i),
COUNT(*) OVER (PARTITION BY (SELECT NULL))
FROM #T)
SELECT
AVG(i) AS Median
FROM t
WHERE (c%2=1 AND n=((c-1)/2)+1) OR (c%2=0 AND (n=c/2 OR n=c/2+1));



I tested this against Louis' solution (Brilliant use of NTILE BTW) and, though it appears to produce a better query plan (more parallelism, lower est. query cost) it runs about the same speed as what Louis put together (~7 seconds/1 million rows on my crappy test box [4-cpu, 4gb ram test]).

Edit: code formatting messed up.

-- Alan Burstein



Best practices for getting help on SQLServerCentral
Need to split a string? Try DelimitedSplit8K or DelimitedSplit8K_LEAD (SQL 2012+)
Need a pattern-based splitter? Try PatternSplitCM
Need to remove or replace those unwanted characters? Try PatExclude8K and PatReplace8K.

"I can't stress enough the importance of switching from a 'sequential files' mindset to 'set-based' thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code. " -- Itzek Ben-Gan 2001
dkschill
dkschill
Mr or Mrs. 500
Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)

Group: General Forum Members
Points: 587 Visits: 430
Thanks for your reply! I am always looking to learn more.
Alan.B
Alan.B
SSCertifiable
SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)SSCertifiable (5.2K reputation)

Group: General Forum Members
Points: 5162 Visits: 7725
TheSQLGuru (7/30/2013)
Fortunately for you SQL 2012 has much better Windowing Function support. Look into the PERCENTILE_CONT function. I also HIGHLY recommend you purchase Itzik Ben-Gan's SQL Server 2012 High-Performance TSQL Using Window Functions book.


Just an interesting FYI...

I have never used PERCENTILE_CONT but I do have Server 2012 High-Performance TSQL Using Window Functions. With the same sample data from earlier (#T), this is a modified version of Ben-Gan's 2012-based solution using PERCENTILE_COUNT:


WITH t(r,m) AS
( SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)),
PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER BY i) OVER(PARTITION BY NULL)
FROM #T
)
SELECT m AS median
FROM t
WHERE r=1;



Though it is much simpler, Ben-Gan's 2012-PERCENTILE_CONT solution is about twice as slow as any other solution posted thus far. Again, just an FYI.

-- Alan Burstein



Best practices for getting help on SQLServerCentral
Need to split a string? Try DelimitedSplit8K or DelimitedSplit8K_LEAD (SQL 2012+)
Need a pattern-based splitter? Try PatternSplitCM
Need to remove or replace those unwanted characters? Try PatExclude8K and PatReplace8K.

"I can't stress enough the importance of switching from a 'sequential files' mindset to 'set-based' thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code. " -- Itzek Ben-Gan 2001
dkschill
dkschill
Mr or Mrs. 500
Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)Mr or Mrs. 500 (587 reputation)

Group: General Forum Members
Points: 587 Visits: 430
Thanks for the example!
Stefan_G
Stefan_G
SSC-Addicted
SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)SSC-Addicted (499 reputation)

Group: General Forum Members
Points: 499 Visits: 960
The original query can be formulated a little bit more elegantly as this:

;WITH t(i,n,c) AS
( SELECT i,
ROW_NUMBER() OVER (ORDER BY i),
COUNT(*) OVER (PARTITION BY (SELECT NULL))
FROM #T)
SELECT
AVG(i) AS Median
FROM t
WHERE 2*n-c BETWEEN 0 AND 2;



This version should be slightly faster because of the simpler expression in the WHERE clause

/SG
Koen Verbeeck
Koen Verbeeck
One Orange Chip
One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)One Orange Chip (27K reputation)

Group: General Forum Members
Points: 27375 Visits: 13268
TheSQLGuru (7/30/2013)
Fortunately for you SQL 2012 has much better Windowing Function support. Look into the PERCENTILE_CONT function. I also HIGHLY recommend you purchase Itzik Ben-Gan's SQL Server 2012 High-Performance TSQL Using Window Functions book.


+1 great book!


How to post forum questions.
Need an answer? No, you need a question.
What’s the deal with Excel & SSIS?
My blog at SQLKover.

MCSE Business Intelligence - Microsoft Data Platform MVP
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search