取SQL Server中的计算中位数

时间:2010-10-12 17:48:09

标签: sql-server median

SQL Server中的MyTable包含_TimeStamp,Column1,Column2和Column3,它们具有以下值:

_TimeStamp Column1 Column2 Column3  
'2010-10-11 15:55:25.40' 10  3  0.5  
'2010-10-11 15:55:25.50' 20  9  0.7  
'2010-10-11 15:55:25.60' 15  2  1.3  
'2010-10-11 15:55:25.70' 17  8  2.7  
'2010-10-11 15:55:25.80' 42  6  3.6  
'2010-10-11 15:55:25.90' 14  2  0.4  

我想找到4 * Column1 * Column2 * Column3的median值。每行的产品是:
           60个
          504个
          156个
       1468.8
       3628.8
         44.8
由于存在偶数个条目,因此中值是两个“中间”条目(156和504)或330的平均值。此外,我只想对落在所选时间范围内的值执行中值,并且解决方案无法改变不属于我的数据库。我编辑了similar query以获取下面显示的查询,但由于列名无效而失败。有什么建议?

SELECT
  AVG(4*Column1*Column2*Column3)
  FROM 
(
  SELECT
    4*Column1*Column2*Column3,
    ROW_NUMBER() OVER (
    ORDER BY 4*Column1*Column2*Column3 ASC, _TimeStamp ASC) AS RowAsc,
    ROW_NUMBER() OVER (
    ORDER BY 4*Column1*Column2*Column3 DESC, _TimeStamp DESC) AS RowDesc
  FROM MyTable WHERE 
   _TimeStamp BETWEEN '2010-10-11 15:55:25.40' AND '2010-10-11 15:55:25.90' 

) x
WHERE 
  RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)

1 个答案:

答案 0 :(得分:1)

我认为您对候选语句所要做的就是在子查询中对计算值进行别名,然后在外部查询中请求AVG别名

SELECT
  AVG(MyValue)
  FROM 
(
  SELECT
    4*Column1*Column2*Column3 AS MyValue,
    ROW_NUMBER() OVER (
    ORDER BY 4*Column1*Column2*Column3 ASC, _TimeStamp ASC) AS RowAsc,
    ROW_NUMBER() OVER (
    ORDER BY 4*Column1*Column2*Column3 DESC, _TimeStamp DESC) AS RowDesc
  FROM MyTable WHERE 
   _TimeStamp BETWEEN '2010-10-11 15:55:25.40' AND '2010-10-11 15:55:25.90' 

) x
WHERE 
  RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)

我没有测试过这个。