我想在一段時間內(例如:過去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
它的工作,但我想知道如果我能以最好的方式做這件事。
感謝,
是的,我想的平均值。我仍然在學習:我不應該平均使用AVG? – Bob
你應該看看這篇關於使用帶日期的快捷方式的文章。 http://sqlblog.com/blogs/aaron_bertrand/archive/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations.aspx –