我一直在努力计算一整天的第50个百分位,我想我已经接近了,但我有点卡住了。
这是普通代码,没有percentile_cont
:
declare @st_date datetime;
declare @en_date datetime;
declare @days int;
set @en_date = (@en_datein);
set @st_date = (@st_datein);
select
srt.Name,
cast(sum(sr.price) as int) as AvgCost,
cast(sum(sr.cost) as int) as AvgTransCost,
cast(avg(sr.TotalTimeSpent) as int) as TotalTimeSpent
from
ServiceReq sr, ServiceReqTemplate srt
where
sr.SvcReqTmplLink_RecID = srt.RecId
and sr.CreatedDateTime >= @st_date
and sr.CreatedDateTime <= @en_date
group by
srt.Name
order by
1
这是我添加percentile_cont
时的代码:
declare @st_date datetime;
declare @en_date datetime;
declare @days int;
set @en_date = (@en_datein);
set @st_date = (@st_datein);
SELECT srt.Name,
percentile_cont(.5) WITHIN GROUP(ORDER BY sr.price) OVER(PARTITION BY srt.Name) AS MedianSpend,
cast(sum(sr.price) as int) as AvgCost,
cast(sum(sr.cost) as int) as AvgTransCost,
cast(avg(sr.TotalTimeSpent) as int) as TotalTimeSpent
from
ServiceReq sr, ServiceReqTemplate srt
where
sr.SvcReqTmplLink_RecID = srt.RecId
and sr.CreatedDateTime >= @st_date
and sr.CreatedDateTime <= @en_date
group by
srt.Name
order by
1
如果我尝试执行此操作,我会收到错误:
列sr.price在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中
我已经google了这个错误,并且已经在StackOverFlow上阅读了,但我还没有解决这个问题。我尝试添加第二个Group By,但是我很困惑我应该使用哪个变量,或者我是否正确地执行此操作!!
如何在相同的Select语句下使用castntile_cont代码使用强制转换代码?
答案 0 :(得分:1)
我不确定它会给你所需的输出,但它会修复错误。 试试这个
percentile_cont(.5) WITHIN GROUP(ORDER BY sum(sr.price)) OVER(PARTITION BY srt.Name) AS MedianSpend
完整陈述
declare @st_date datetime;
declare @en_date datetime;
declare @days int;
set @en_date = (@en_datein);
set @st_date = (@st_datein);
SELECT srt.Name,
percentile_cont(.5) WITHIN GROUP(ORDER BY sum(sr.price)) OVER(PARTITION BY srt.Name) AS MedianSpend,
cast(sum(sr.price) as int) as AvgCost,
cast(sum(sr.cost) as int) as AvgTransCost,
cast(avg(sr.TotalTimeSpent) as int) as TotalTimeSpent
from
ServiceReq sr, ServiceReqTemplate srt
where
sr.SvcReqTmplLink_RecID = srt.RecId
and sr.CreatedDateTime >= @st_date
and sr.CreatedDateTime <= @en_date
group by
srt.Name
order by
1