在T-SQL中使用percentile_cont和“group by”语句

时间:2013-10-23 15:56:20

标签: sql-server tsql group-by

我想使用percentile_cont函数在T-SQL中获取中值。但是,我也需要获得平均值。我想做类似以下的事情:

SELECT  CustomerID ,
    AVG(Expenditure) AS MeanSpend , percentile_cont
    ( .5) WITHIN GROUP(ORDER BY Expenditure) OVER( ) AS MedianSpend
FROM    Customers
GROUP BY CustomerID

这可以实现吗?我知道我可以使用OVER子句对percentile_cont结果进行分组......

但是后来我使用了两个查询,我不是吗?

2 个答案:

答案 0 :(得分:8)

刚想通了......要放弃小组,并给两个聚合函数一个过度的声明。

SELECT CustomerID,
    AVG(Expenditure) OVER(PARTITION BY CustomerID) AS MeanSpend,
    percentile_cont(.5) WITHIN GROUP(ORDER BY Expenditure) OVER(PARTITION BY CustomerID) AS MedianSpend
FROM Customers

答案 1 :(得分:1)

您不能对窗口功能使用“分组依据”。这些函数返回每行的聚合值。一种方法是使用“select distinct”来摆脱重复的行。只需确保按非聚合列(本例中为groupId)对每个窗口函数进行分区。

--Generate test data
SELECT  TOP(10) 
    value.number%3  AS  groupId
,   value.number    AS  number
INTO    #data
FROM  master.dbo.spt_values  AS  value
WHERE value."type" = 'P' 
ORDER BY NEWID()
;

--View test data
SELECT  * FROM #data ORDER BY groupId,number;

--CALCULATE MEDIAN
SELECT DISTINCT 
    groupId
,   AVG(number)                                         OVER(PARTITION BY groupId)  AS mean
,   percentile_cont(.5) WITHIN GROUP(ORDER BY number)   OVER(PARTITION BY groupId)  AS median
FROM    #data
;

--Clean up
DROP TABLE #data;