Link to home
Start Free TrialLog in
Avatar of sharon2011
sharon2011

asked on

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
BusinessUnit,    
FullName,
CAST(DATEDIFF(dd, 0,  CreatedOn) AS datetime) as CreatedOn,
Count( QuoteId) as Quotes
FROM        
      quote  
WHERE
       BusinessUnit IN (@BusinessUnit)
      AND (CAST(DATEDIFF(dd, 0, CreatedOn) AS datetime) BETWEEN @StartDate AND @EndDate)
GROUP BY
      BusinessUnit,
      FullName,
      CAST(DATEDIFF(dd, 0,  CreatedOn) AS datetime)
)

,Median_all as
(
SELECT DISTINCT BusinessUnit, Quotes,
    PERCENTILE_CONT(0.5)
        WITHIN GROUP (ORDER BY Quotes)
        OVER (PARTITION BY BusinessUnit) AS MedianContAll
FROM QuoteCount
WHERE @BusinessUnit= null
ORDER BY BusinessUnit DESC
)

,Median as
(
SELECT DISTINCT  BusinessUnit, Quotes,
    PERCENTILE_CONT(0.5)
        WITHIN GROUP (ORDER BY Quotes)
        OVER (PARTITION BY BusinessUnit) AS MedianCont
FROM QuoteCount
WHERE BusinessUnit in (@BusinessUnit)
ORDER BY BusinessUnit DESC
)
select
qc.BusinessUnit,
qc.fullname,
qc.CreatedOn,
sum(qc.Quotes) as Quotes,
max(m.MedianCont) as MedianCont,
max(ma.MedianContAll ) as MedianContAll
from
      Median_all ma  
         inner join Median m  on m.BusinessUnit=ma.BusinessUnit
      inner join QuoteCount qc on ma.BusinessUnit=qc.BusinessUnit
group by
qc.BusinessUnit,
qc.fullname,
qc.CreatedOn
order by
qc.BusinessUnit,
qc.fullname,
qc.CreatedOn

Thank you in advance.
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sharon2011
sharon2011

ASKER

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.