2010-10-12 131 views
1

的MyTable在SQL Server包含_TimeStamp,列1,列2和欄3,它有以下值:以計算平均在SQL Server

_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 *列1的median值*列2 *欄3。該產品爲每一行是:
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

我認爲,所有你需要做的,你的候選語句在子查詢別名計算的值,然後索要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) 

我還沒有測試過。

+0

工作很好!謝謝! – KAE 2010-10-12 18:01:42