2014-10-30 178 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