2014-10-30 155 views
0

我一直试图计算整个字段的第50百分位,并且我认为我越来越接近了,但我有点卡住了。SQL Server 2012函数“Percentile_Cont” - GROUP BY问题

这是正常的代码,而无需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 

如果我尝试执行此我收到的错误:

Column sr.price is invalid in the select list because is not contained in either an aggregate function or the GROUP BY clause

我已经使用了这个错误,并且一直在StackOver上阅读流量,但我还没有解决这个问题。我尝试添加第二个分组依据,但我很困惑我应该使用哪个变量,或者如果我正确地做到了这一点!

如何让percentntile_cont代码在同一个Select语句下与演员代码一起工作?

+1

[不良习惯踢:使用旧样式的JOIN(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/ 08/bad-habits-to-kick-using-old-style-joins.aspx) - 旧式*逗号分隔的表*样式列表被替换为ANSI中的适当* ANSI'JOIN'语法 - ** 92 ** SQL标准(**超过20年**前),其使用是不鼓励 – 2014-10-30 05:50:43

+0

它是一个开箱即用的报告,我自定义 – QuestionQuestion 2014-10-30 12:55:13

回答

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 
+0

非常感谢!我可以运行它,但我无法显示中值。 – QuestionQuestion 2014-10-30 12:52:18

+0

说我不想要总和(sr.price),而只想要ORDER BY(sr.price),我怎么能在没有收到集合函数错误的情况下完成这个任务。 – QuestionQuestion 2014-10-30 13:38:19