2012-03-16 166 views
4

我有一個包含2個字段的SQL表:TimeStamp和Value。以下是一些數據的摘錄。以小時計算SQL平均值

2005-02-17 13:31:00  2 
2005-02-17 13:46:00  3 
2005-02-17 14:01:00  1.7 
2005-02-17 14:16:00  2.3 
2005-02-17 14:31:00  2 
2005-02-17 14:46:00  2.5 
2005-02-17 15:01:00  2.2 
2005-02-17 15:16:00  2.4 
2005-02-17 15:31:00  2.6 
2005-02-17 15:46:00  2.6 
2005-02-17 16:01:00  2.7 

我想每小時取平均值的列,但我似乎無法使這項工作正確。最終輸出將顯示TimeStamp的開始小時數以及Value列的平均值。

對於最終的輸出結果,我期望得到一個完整的時間戳結果,而不僅僅是小時。因此,從14:00 - 14:59在2005-02-17輸出結果將是:

2005-02-17 14:00:00 2.125 
+0

這是什麼類型的數據庫? – dldnh 2012-03-16 20:38:03

+0

@dldnh這是sql服務器。點擊標籤([tag:tsql])以獲得想法 – 2012-03-16 20:41:08

+0

這是一個t?對我的眼睛來說太小了 - 對此感到遺憾! – dldnh 2012-03-16 20:42:11

回答

3

我會這樣做:

SELECT  CAST(FLOOR(CAST(timestamp AS float)) AS datetime) AS day --strip time 
      , DATEPART(hh, timestamp) AS hour 
      , AVG(value) AS average 
FROM  times 
GROUP BY CAST(FLOOR(CAST(timestamp AS float)) AS datetime) 
      , DATEPART(hh, timestamp) 

示例fiddle

+0

這很好。無論如何要把時間放回時間戳嗎? – Andrew 2012-03-19 16:44:30

+0

是的,我的解決方案顯示如何;-) – 2012-03-19 17:12:15

3
SELECT DATEPART(hour,Col1) as hourcol,AVG(Col2) 
FROM Yourtable 
GROUP BY hourcol; 

OR

SELECT SUBSTRING(Col1,1,14)+'00' AS hourcol,AVG(Col2) 
FROM Yourtable 
GROUP BY hourcol; 

在此查詢DATEPART函數計算所有的小時值在DATETIME列中的值和基於每小時的第二列的平均值在小時級別計算。

+0

這可行,但在GROUP BY子句中,我想按日期和小時分組。因此,對於2005-02-17 14:00到2005-02-17 14:59的時間間隔,我希望TimeStamp列顯示2005-02-17 14:00,而不是僅顯示14. – Andrew 2012-03-16 20:56:26

+0

好的..如果這是案例嘗試使用子字符串和concat函數一起得到所需的輸出...試試看n告訴我...如果你沒有得到它,我會幫你的答案... – Teja 2012-03-16 22:12:36

+0

這隻需要「小時「,但他需要約會和約會。例如:SELECT DATEPART(小時,'2012-03-19 09:12')結果「9」,但他需要「2012-03-19 09:00」 – adyusuf 2012-03-19 07:13:02

0

我想你也希望它按日期分組,不僅按小時,對吧?

select 
    convert(VARCHAR(10), date, 111) as aDate, 
    datepart(HH, date) anHour, 
    avg(value) anAverage 
from t 
group by convert(VARCHAR(10), date, 111), datepart(HH, date) 

或者這樣:

; with aTable as (
select 
    convert(VARCHAR(10), date, 111) as aDate, 
    datepart(HH, date) anHour, 
    value 
from t) 
select aDate, anHour, avg(value) from aTable 
group by aDate, anHour 
0
SELECT 
    AVG(myvalue) [Average], 
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime)) [Hour] 
FROM 
    myTable 
GROUP BY 
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime)) 
ORDER BY 
    DATEADD(HOUR, DATEPART(HOUR, mydate), CAST(CAST(mydate as Date) as datetime)) 
4
select Time_Stamp_Hour=dateadd(hh,datepart(hh,Time_Stamp), cast(CAST(Time_Stamp as date) as datetime)) 
, AvgValue=AVG(Value) 
from ValueLog 
group by dateadd(hh,datepart(hh,Time_Stamp), cast(CAST(Time_Stamp as date) as datetime)) 

結果:

Time_Stamp_Hour   AvgValue 
----------------------- ---------------------- 
2005-02-17 13:00:00.000 2.5 
2005-02-17 14:00:00.000 2.125 
2005-02-17 15:00:00.000 2.45 
2005-02-17 16:00:00.000 2.7 

兼容性:SQL服務器2008+