Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
CREATE TABLE sampleData ( groupID int, numValue int )
INSERT INTO sampleData VALUES ( 1, 1 )
INSERT INTO sampleData VALUES ( 1, 2 )
INSERT INTO sampleData VALUES ( 1, 6 )
INSERT INTO sampleData VALUES ( 1, 16 )
INSERT INTO sampleData VALUES ( 1, 7 )
INSERT INTO sampleData VALUES ( 2, 5 )
INSERT INTO sampleData VALUES ( 2, 5 )
INSERT INTO sampleData VALUES ( 2, 5 )
INSERT INTO sampleData VALUES ( 2, 11 )
INSERT INTO sampleData VALUES ( 3, 10 )
INSERT INTO sampleData VALUES ( 3, 17 )
INSERT INTO sampleData VALUES ( 3, 52 )
INSERT INTO sampleData VALUES ( 3, 66 )
INSERT INTO sampleData VALUES ( 4, 18 )
INSERT INTO sampleData VALUES ( 5, 0 )
INSERT INTO sampleData VALUES ( 5, 0 )
DECLARE @groupID int; SET @groupID = 1
DECLARE @M1 int, @M2 int
SELECT TOP 50 PERCENT @M1 = numValue FROM sampleData WHERE groupID = @groupID ORDER BY numValue ASC
SELECT TOP 50 PERCENT @M2 = numValue FROM sampleData WHERE groupID = @groupID ORDER BY numValue DESC
SELECT (@M1+@M2)/2.0
CREATE FUNCTION fn_getMedian( @groupID int )
RETURNS decimal(5, 3)
AS
BEGIN
DECLARE @m1 int, @m2 int, @ret decimal(5, 3)
SELECT TOP 50 PERCENT @m1= numValue FROM sampleData WHERE groupID=@groupID ORDER BY numValue ASC
SELECT TOP 50 PERCENT @m2= numValue FROM sampleData WHERE groupID=@groupID ORDER BY numValue DESC
SET @ret = (@m1+@m2)/2.0
RETURN @ret
END
GO
SELECT groupID, dbo.fn_getMedian( groupID)
FROM sampleData
GROUP BY groupID
ORDER BY groupID
DECLARE @temp TABLE( rownum int identity(1, 1), GroupID int, numValue int )
INSERT INTO @temp( groupID, numValue )
SELECT groupID, numValue
FROM SampleData
ORDER BY groupID, numValue
SELECT A.groupID, AVG(1.0*A.NumValue) AS medianValue
FROM @temp A
INNER JOIN
( SELECT groupID, FLOOR(AVG(1.0*rownum)) AS m1, CEILING(AVG(1.0*rownum)) AS m2
FROM @temp
GROUP BY groupID
) B
ON A.groupID = B.groupID AND A.rownum BETWEEN B.m1 AND B.m2
GROUP BY A.groupID
SELECT R.groupID, AVG(1.0*R.numValue) AS medianValue
FROM
( SELECT GroupID, numValue, ROW_NUMBER() OVER(PARTITION BY groupID ORDER BY NumValue) AS rowno
FROM sampleData
) R
INNER JOIN
( SELECT GroupID, 1+count(*) as N
FROM sampleData
GROUP BY GroupID
) G
ON R.GroupID = G.GroupID AND R.rowNo BETWEEN N/2 AND N/2+N%2
GROUP BY R.groupID
SET ANSI_WARNINGS OFF
SELECT groupID, CASE WHEN cnt%2=1 THEN t1max ELSE (t1max+t2min)/2.0 END AS medianValue
FROM
( SELECT groupID, COUNT(numValue) AS cnt,
MAX(CASE WHEN tile=1 THEN numValue END) AS t1max,
MIN(CASE WHEN tile=2 THEN numValue END) AS t2min
FROM
( SELECT groupID, numValue, NTILE(2) OVER( PARTITION BY groupID ORDER BY numValue ) AS tile
FROM sampleData
) T
GROUP BY T.groupID
) G
ORDER BY groupID