2013-04-01 196 views
0

我每天早上只要我的機器打開啓動記錄數據溫度計第一個記錄。選擇與聚合函數

我想選擇最小,最大和平均溫度,以及溫度在機器開啓和關閉每天當。

我的表結構如下:

時登錄,登錄日期,溫度通過登錄來獲得當天的日期聚集

I組,但我似乎無法找到一個好辦法選擇記錄的第一個和最後一個時間戳的溫度。

任何幫助?

回答

0

你想使用Windows函數是這樣的:

select t.DateLogged, min(t.Temperature), max(t.Temperature), avg(t.Temperature), 
     max(case when t.seqnum_asc = 1 then t.Temperature end) as FirstTemperature, 
     max(case when t.seqnum_desc = 1 then t.Temperature end) as LastTemperature, 
from (select t.*, 
      row_number() over (partition by dateLogged order by timeLogged) as seqnum_asc, 
      row_number() over (partition by dateLogged order by timeLogged desc) as seqnum_desc 
     from t 
    ) t 
group by t.DateLogged 
order by DateLogged 

這是什麼東西做的是增加了兩個新的變量。從1開始的第一天(seqnum_asc)列舉一天中的值。其他枚舉有1 for the last reading ( seqnum_desc`)。

要得到的值,使用條件求和。

如果你喜歡,你其實可以做很多使用min()max()作爲窗口fucnctions同樣的事情,而不是row_number()

select t.DateLogged, min(t.Temperature), max(t.Temperature), avg(t.Temperature), 
     max(case when timeLogged = mintime then t.Temperature end) as FirstTemperature, 
     max(case when timeLogged = maxtime then t.Temperature end) as LastTemperature, 
from (select t.*, 
       min(timeLogged) over (partition by dateLogged) as minTime, 
      max(timeLogged) over (partition by dateLogged) as maxTime 
     from t 
    ) t 
group by t.DateLogged 
order by DateLogged