选择具有聚合函数的第一条记录

时间:2013-04-01 14:47:48

标签: sql sql-server report aggregates

我有一个温度计,每当我的机器开启时,它就会开始记录数据。

我想选择最低,最高和平均温度,以及机器每天开启和关闭时的温度。

我的表格结构如下:

记录时间,记录日期,温度

我按日期分组记录以获取当天的聚合,但我似乎无法找到一个很好的方法来选择记录的第一个和最后一个时间戳的温度。

任何帮助?

1 个答案:

答案 0 :(得分: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

这样做是添加两个新变量。一个用第一个读数(seqnum_asc)枚举从1开始的值。另一个枚举有1 for the last reading ( seqnum_desc`)。

要获取值,请使用条件求和。

如果您愿意,使用min()max()作为窗口功能,而不是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