函数计算SQLServer中的中位数根据MSDN,中位数在Transact-SQL中不能作为聚合函数使用。但是,我想知道是否可以创建此功能(使用创建聚合函数、用户定义函数或其他方法)。最好的方法(如果可能的话)是什么?允许在聚合查询中计算中值(假设是数字数据类型)?
3 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
SELECT CustomerId, AVG(TotalDue)FROM( SELECT CustomerId, TotalDue, -- SalesOrderId in the ORDER BY is a disambiguator to break ties ROW_NUMBER() OVER ( PARTITION BY CustomerId ORDER BY TotalDue ASC, SalesOrderId ASC) AS RowAsc, ROW_NUMBER() OVER ( PARTITION BY CustomerId ORDER BY TotalDue DESC, SalesOrderId DESC) AS RowDesc FROM Sales.SalesOrderHeader SOH) xWHERE RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)GROUP BY CustomerIdORDER BY CustomerId;
子衿沉夜
TA贡献1828条经验 获得超3个赞
SELECT( (SELECT MAX(Score) FROM (SELECT TOP 50 PERCENT Score FROM Posts ORDER BY Score) AS BottomHalf) + (SELECT MIN(Score) FROM (SELECT TOP 50 PERCENT Score FROM Posts ORDER BY Score DESC) AS TopHalf)) / 2 AS Median
添加回答
举报
0/150
提交
取消