views:

15

answers:

1

Here's my table

ST NUM
1 1
1 2
1 2
2 1
2 2
2 2
3 2
3 8

I want to return a query where it returns the median of NUM for each ST

ST NUM
1 2
2 2
3 5

I already have a median function

SELECT
CONVERT(DECIMAL(10,2), (
(CONVERT (DECIMAL(10,2),
(SELECT MAX(num) FROM
(SELECT TOP 50 PERCENT num FROM dbo.t ORDER BY num ASC) AS H1)
+
(SELECT MIN(sortTime) FROM
(SELECT TOP 50 PERCENT num FROM dbo.t ORDER BY num DESC) AS H2)
))) / 2) AS Median

Any tips for how to do this?

+1  A: 

try this

With
MedianResult
as
(
Select
ST,NUM ,   
Row_Number() OVER(Partition by ST Order by NUM) as A,
Row_Number() OVER(Partition by ST Order by NUM desc) as B
from **YourTableName**

)
Select ST, Avg(NUM) as Median
From MedianResult
Where Abs(A-B)<=1
Group by ST
Raymund