【发布时间】:2014-12-26 00:34:21
【问题描述】:
我整天都在尝试计算某个字段的第 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 子句中
我已经用谷歌搜索了这个错误,并且一直在阅读 StackOverFlow,但我还没有解决这个问题。我尝试添加第二个 Group By,但我不知道我应该使用哪个变量,或者我是否正确地这样做了!!
如何使 percentile_cont 代码与同一 Select 语句下的强制转换代码一起工作??
【问题讨论】:
-
Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI
JOIN语法-92 SQL 标准(20 多年前),不鼓励使用它 -
它是我正在自定义的开箱即用报告
标签: sql reporting-services sql-server-2012 reporting percentile