2017-03-21 80 views
0

我想在一段時間內(例如:過去6個月,上個月,上週...)有平均水平。如何計算一段時間內的平均值?

爲此,我創建了4個查詢。我能清楚地做點什麼嗎?

/** ON SELECTED DATE*/ 
SELECT AVG(RUN_TIME) 
FROM (SELECT (DATEDIFF(minute,MIN(CAST(START_DATE AS DATETIME)), MAX(CAST(END_DATE AS DATETIME)))) as RUN_TIME FROM TableTest where DATE_EXPECTED = DATE_SELECTED) f 

/**ON 6 last month*/ 
SELECT AVG(RUN_TIME) 
FROM (SELECT (DATEDIFF(minute,MIN(CAST(START_DATE AS DATETIME)), MAX(CAST(END_DATE AS DATETIME)))) as RUN_TIME FROM TableTest 
where Month(CAST(DATE_SELECTED AS DATETIME)) BETWEEN Month(CAST(DATE_SELECTED AS DATETIME)) AND Month(CAST(DATE_SELECTED AS DATETIME))+6) f 

/** on 30 last days */ 
SELECT AVG(RUN_TIME) 
FROM (SELECT (DATEDIFF(minute,MIN(CAST(START_DATE AS DATETIME)), MAX(CAST(END_DATE AS DATETIME)))) as RUN_TIME FROM TableTest where DATE_EXPECTED between DATE_SELECTED and DATE_SELECTED+30) f 

/* on 5 last days */ 
SELECT AVG(RUN_TIME) 
FROM (SELECT (DATEDIFF(minute,MIN(CAST(START_DATE AS DATETIME)), MAX(CAST(END_DATE AS DATETIME)))) as RUN_TIME FROM TableTest where DATE_EXPECTED between DATE_SELECTED and DATE_SELECTED+5) f 

它的工作,但我想知道如果我能以最好的方式做這件事。

感謝,

+0

是的,我想的平均值。我仍然在學習:我不應該平均使用AVG? – Bob

+0

你應該看看這篇關於使用帶日期的快捷方式的文章。 http://sqlblog.com/blogs/aaron_bertrand/archive/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations.aspx –

回答

2

可以使用條件彙總:

SELECT AVG(CASE WHEN DATE_EXPECTED = DATE_SELECTED THEN RUN_TIME END) as avg_1, 
     AVG(CASE WHEN Month(CAST(DATE_SELECTED AS DATETIME)) BETWEEN Month(CAST(DATE_SELECTED AS DATETIME)) AND Month(CAST(DATE_SELECTED AS DATETIME))+6 THEN RUN_TIME END) as avg_2, 
     AVG(CASE WHEN DATE_EXPECTED between DATE_SELECTED and DATE_SELECTED+30 THEN RUN_TIME END) as avg_3, 
     AVG(CASE WHEN DATE_EXPECTED between DATE_SELECTED and DATE_SELECTED+5 THEN RUN_TIME END) as avg_4 
FROM (SELECT (DATEDIFF(minute,MIN(CAST(START_DATE AS DATETIME)), MAX(CAST(END_DATE AS DATETIME)))) as RUN_TIME 
     FROM TableTest 
    ) f; 
+0

我沒有相同的結果作爲我不同的疑問。我所有的平均結果相同(不應該) – Bob

+0

@FannyV。 。 。這四個'avg()'調用的數據必須非常特別,以返回相同的值。 –