【问题标题】:SQL Server 2012 Function "Percentile_Cont" - GROUP BY issueSQL Server 2012 函数“Percentile_Cont”-按问题分组
【发布时间】: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


【解决方案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

【讨论】:

  • 非常感谢!!我可以运行它,但我仍然无法显示中位数。
  • 说我不想要 sum(sr.price),而只想要 ORDER BY (sr.price),我怎样才能在不收到聚合函数错误的情况下做到这一点。
猜你喜欢
  • 2011-06-20
  • 2016-05-26
  • 2010-10-10
  • 2014-10-29
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
相关资源
最近更新 更多