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.
1 1
2 2
7 3
8
7
9 8
9
DECLARE @Median decimal(9,4)
, @mid int, @odd int, @mid1 int, @mid2 int
, @NumRows int
CREATE TABLE #Prices (
ID int IDENTITY(1,1)
, Price decimal(9,4)
)
INSERT INTO #Prices (Price)
SELECT Price
FROM PriceTable
ORDER BY Price
SET @NumRows = @@ROWCOUNT
SET @odd = @NumRows % 2 --1 if odd number of rows, 0 if even
SET @mid = @NumRows / 2 --Number of the "middle" record
IF @NumRows = 1 BEGIN --Special trick so this works if only one record
SET @odd = 1
SET @mid = 1
END
-- Which row(s) hold the median value?
IF @odd = 1 BEGIN
--Odd number of rows - median is the middle one
SET @Median = (SELECT Price FROM #Prices WHERE ID = @mid)
END ELSE BEGIN
--Even number of rows - median is the average of the two middle ones
SET @mid1 = (SELECT Number FROM #Prices WHERE ID = @mid)
SET @mid2 = (SELECT Number FROM #Prices WHERE ID = @mid + 1)
SET @Median = (@mid1 + @mid2) / 2
END
SELECT @Median
--Holding table for median rows
CREATE TABLE #Prices (
ID int IDENTITY(1,1)
, Price decimal(9,4)
)
DECLARE @Age int, @Median decimal(9,4)
, @mid int, @odd int, @mid1 int, @mid2 int
, @NumRows int
DECLARE oCursor CURSOR FOR
SELECT DISTINCT Age
FROM PricesByAge
ORDER BY Age ASC
--Open said cursor and start stepping thru it
OPEN oCursor
WHILE 0=0 BEGIN
FETCH NEXT FROM oCursor INTO @Age
IF @@Fetch_Status<>0 BREAK
TRUNCATE TABLE #Prices
--Insert the data for a given age
INSERT INTO #Prices (Price)
SELECT Price
FROM PricesByAge
WHERE Age = @Age
ORDER BY Price
--Now actually compute the median
SET @NumRows = @@ROWCOUNT
SET @odd = @NumRows % 2 --1 if odd number of recs, 0 if even
SET @mid = @NumRows / 2 --Number of the "middle" record
IF @NumRows = 1 BEGIN --Special trick so this works if only one record
SET @odd = 1
SET @mid = 1
END
-- Which row(s) hold the median value?
IF @odd = 1 BEGIN
--Odd number of rows - median is the middle one
SET @Median = (SELECT Price FROM #Prices WHERE ID = @mid)
END ELSE BEGIN
--Even number of rows - median is the average of the two middle ones
SET @mid1 = (SELECT Price FROM #Prices WHERE ID = @mid)
SET @mid2 = (SELECT Price FROM #Prices WHERE ID = @mid + 1)
SET @Median = (@mid1 + @mid2) / 2
END
SELECT @Age AS Age, @Median AS MedianPrice
END
CLOSE oCursor
DEALLOCATE oCursor