在没有Group By的情况下获得每天/小时的平均值

时间:2014-08-11 21:39:13

标签: sql tsql sql-server-2008-r2

在单个表格中,我说我有里程和时间戳的记录。我想得到每天和每小时的平均里程数。由于日期格式,我不能使用固有的“Group By”子句。

以下是一些示例数据:

  Table: tb_mileage
  ===============================================
  f_mileagetimestamp           f_mileage
  -----------------------------------------------
  2014-08-11 11:13:02.000      50                       
  2014-08-11 16:12:55.000      100      
  2014-08-11 16:55:00.000      30                
  2014-08-12 11:12:50.000      80                       
  2014-08-12 16:12:49.000      100                      
  2014-08-13 08:12:46.000      40                       
  2014-08-13 08:45:31.000      100                      

因此,理想的结果集如下所示( PER DAY )(注意,日期格式无关紧要):

  Date                 Average
  ------------------------------------------------
  08/11/2014           60
  08/12/2014           90
  08/13/2014           70

理想的结果集如下所示( PER HOUR )(注意,日期格式无关紧要):

  Date                     Average
  ------------------------------------------------
  08/11/2014 11:00:00      50
  08/11/2014 16:00:00      65
  08/12/2014 11:00:00      80
  08/12/2014 16:00:00      100
  08/13/2014 08:00:00      70

请注意,此处的示例纯粹是理论上的和简化的,并不一定反映实际实施所需的确切标准。这仅仅是为了推动我自己的学习,因为我发现做类似事情的所有例子都非常复杂,使学习变得困难。

2 个答案:

答案 0 :(得分:6)

请尝试使用日期版本。

select cast(t.f_mileagetimestamp as date) as dt, avg(t.f_mileage) as avg_mileage
from
tb_mileage t
group by cast(t.f_mileagetimestamp as date)
order by cast(t.f_mileagetimestamp as date) asc;

对于小时版本,您可以使用此功能。

select t2.dt, avg(t2.f_mileage) as avg_mileage
from
(
    select substring(CONVERT(nvarchar(100), t1.f_mileagetimestamp, 121), 1, 13) + ':00' as dt, t1.f_mileage 
    from
    tb_mileage t1
) t2
group by t2.dt
order by t2.dt asc;

答案 1 :(得分:5)

我认为这应该适用于" day"版本:

select cast(f_mileagetimestamp as date), avg(f_mileage)
from tb_mileage
group by cast(f_mileagetimestamp as date)
order by cast(f_mileagetimestamp as date);

小时,我只会使用这个功能:

select cast(f_mileagetimestamp as date), datepart(hour, f_mileagetimestamp), avg(f_mileage)
from tb_mileage
group by cast(f_mileagetimestamp as date), datepart(hour, f_mileagetimestamp)
order by cast(f_mileagetimestamp as date), datepart(hour, f_mileagetimestamp);