• Status: Solved
• Priority: Medium
• Security: Public
• Views: 516

# calculate Median sql 2012

I need to calculate the Median of quotes based on BusinessUnit, and can't figure out why the following  code are not working:

;with QuoteCount as
(
SELECT
FullName,
CAST(DATEDIFF(dd, 0,  CreatedOn) AS datetime) as CreatedOn,
Count( QuoteId) as Quotes
FROM
quote
WHERE
AND (CAST(DATEDIFF(dd, 0, CreatedOn) AS datetime) BETWEEN @StartDate AND @EndDate)
GROUP BY
FullName,
CAST(DATEDIFF(dd, 0,  CreatedOn) AS datetime)
)

,Median_all as
(
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY Quotes)
OVER (PARTITION BY BusinessUnit) AS MedianContAll
FROM QuoteCount
)

,Median as
(
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY Quotes)
OVER (PARTITION BY BusinessUnit) AS MedianCont
FROM QuoteCount
)
select
qc.fullname,
qc.CreatedOn,
sum(qc.Quotes) as Quotes,
max(m.MedianCont) as MedianCont,
max(ma.MedianContAll ) as MedianContAll
from
Median_all ma
group by
qc.fullname,
qc.CreatedOn
order by
qc.fullname,
qc.CreatedOn

0
sharon2011
1 Solution

Chief Technology OfficerCommented:
Probably because of the "@BusinessUnit = NULL" - if you are partitioning by BusinessUnit, you do not need two CTEs.  If your intent is to get the median for everything when @BusinessUnit is NULL, you still can do this with one query.  Can you provide a table creation script and some sample data along with expected results.

In the interim, here is an example of how the median works, explaining the difference between the two new functions in SQL 2012:
http://nobrainerlab.com/2013/05/17/statistical-median-with-t-sql-2012/
http://technet.microsoft.com/en-us/library/hh231473.aspx
0

Author Commented:
Kevin Cross,

Sorry for the delayed response. I removed the @BusinessUnit = Null. Instead Union all the query with all BusinessUnit. Then use the following code:

, ALLBUROWNum as
(
select grp,  cnt, ROW_NUMBER() over (order by  cnt) as n
from AllBUWeightCount

)

,findALLBUMedian as
(
select ceiling(max(n)/2.0) as n
from ALLBUROWNum
union all
select ceiling(max(n)/2.0)+1 as n
from ALLBUROWNum
having max(n) % 2 = 0
)

, AllBUMedian as
(
SELECT C.grp, AVG(1. * c.cnt) AS AllBUMedian
FROM ALLBUROWNum AS C
INNER JOIN findALLBUMedian AS f
on C.n = f.n
GROUP BY C.grp
)

Thank you so much for your immediate assistance.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.