472,986 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,986 software developers and data experts.

The Median Function in SQL Server

I read the follow query about calculating median posted by Daivd Porta
on 10/8/03.

CREATE TABLE SomeValues (keyx CHAR(1) PRIMARY KEY, valuex INTEGER NOT
NULL)

INSERT INTO SomeValues VALUES ('A',1)
INSERT INTO SomeValues VALUES ('B',2)
INSERT INTO SomeValues VALUES ('C',3)
INSERT INTO SomeValues VALUES ('D',4)
INSERT INTO SomeValues VALUES ('E',5)

SELECT S1.valuex AS median
FROM SomeValues AS S1, SomeValues AS S2
GROUP BY S1.valuex
HAVING SUM(CASE WHEN S2.valuex <= S1.valuex
THEN 1 ELSE 0 END)
= ((COUNT(*) + 1) / 2) AND SUM(CASE WHEN S2.valuex >= S1.valuex
THEN 1 ELSE 0 END)= (COUNT(*)/2 + 1)


I have difficulty to understand the having clause. If S1 and S2 are
the same table, what it means by S2.valuex >= S1.valuex? Could some
give me a help?

Also, if I have a table structured as:

classID field1 field2 field3
c1 1 2 3
c1 4 5 6
c1 7 8 9
c2 9 8 7
c2 6 5 4
c2 3 2 1

Is there a way to create a user-defined function that can get the
median for each field as easy as the average function. Such as

select distinct classID,
median(field1),
median(field2),
median(field3)
from [tablename]
group by classID
Thanks in advance
Jul 20 '05 #1
2 20144
It is not very simple to write UDFs for all the aggregate requirements. Not
the best way, but here is one using the data & logic you have posted, though
there is no real need for a table variable:

CREATE FUNCTION dbo.Median ( @cid CHAR( 2 ), @fd INT )
RETURNS INT
AS
BEGIN
DECLARE @t TABLE ( c INT )
INSERT @t SELECT CASE @fd WHEN 1 THEN field1
WHEN 2 THEN field2
WHEN 3 THEN field3
END
FROM tbl
WHERE classID = @cid ;
RETURN ( SELECT c
FROM ( SELECT t1.c,
SUM( CASE WHEN t2.c <= t1.c
THEN 1 ELSE 0 END ),
SUM( CASE WHEN t2.c >= t1.c
THEN 1 ELSE 0 END ),
( COUNT( * ) + 1 ) / 2,
( COUNT( * )/2 + 1 )
FROM @t t1
CROSS JOIN @t t2
GROUP BY t1.c ) D ( c, s1, s2, c1, c2)
WHERE s1 >= c1 AND s2 >= c2 )
END

Now you can have your query with the above UDF like:

SELECT classID,
dbo.Median(classID, 1),
dbo.Median(classID, 2),
dbo.Median(classID, 3)
FROM tbl
GROUP BY classID ;

--
- Anith
( Please reply to newsgroups only )
Jul 20 '05 #2
> the same table, what it means by S2.valuex >= S1.valuex? Could some
give me a help?


The query is a Cross Join, which is difficult to avoid when calculating the
Median. The two SUM(CASE...) expressions compare every S1 value to every S2
value and the HAVING clause says that the count of values where S2 <= S1 and
the count of values where S2 >= S1 must both be >= COUNT(*)/2 (= the
middle).

I didn't devise this solution but it's one of a number of alternative median
queries that you'll find if you search the archives of the SQLServer groups.

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Ross Contino | last post by:
Hello to all: I have been searching the web for examples on how to determine a median value in a mySQL table. I have reviewed the article at...
2
by: Bob | last post by:
I have been looking at the code for MedianFind(pDte As String) from the following thread from UtterAccess.com: "Finding Median average grouped by field" I have been able to get it to run using...
8
by: nick.vitone | last post by:
Hi, I'm somewhat of a novice at Access, and I have no experience programming whatsoever. I'm attempting to calculate the statistical median in a query. I need to "Group by" one column and find...
4
by: uspensky | last post by:
I have a table (cars) with 3 fields: VIN, Class, sell_price 101, sports, 10000 102, sports, 11000 103, luxury, 9000 104, sports, 11000 105, sports, 11000 106, luxury, 5000 107, sports, 11000
5
by: jonm4102 | last post by:
I'm trying to calculate the median of some numerical data. The data can only be found in a query (henceforth query 1) field I previously made, and I would prefer to calculate the median in a new...
1
by: Jaime Leivers | last post by:
Here's a median function in access that you can call in any query. You could change this to any excel function you wanted. Most people can find the windows help file that says how to call an excel...
3
by: Scott | last post by:
I need to take the median from a field of records in a report. Can someone shed the light how to do it. Thanks, Scott
3
by: mehwishobaid | last post by:
i dont know wat is wrong with my code. when i compile. i get the error saying line 29: error: expression must have pointer-to-object type #include <iostream> using namespace std; #include...
6
by: rrstudio2 | last post by:
I am using the following vba code to calculate the median of a table in MS Access: Public Function MedianOfRst(RstName As String, fldName As String) As Double 'This function will calculate the...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.