0

I have a scenario I need help with. I have to create a sql query using SQL Server 2000 that will do the following:

I have data that looks like the table below. I need to find a way to determine an average temparture every 3 hours. The tricky part is the every 3 hour grouping should be like the following:

1st Average Grouping - (03/01/2013 13:00, 03/01/2013 14:00, 03/01/15:00)
2nd Average Grouping - (03/01/2013 14:00, 03/01/2013 15:00, 03/01/16:00)
3rd Average Grouping - (03/01/2013 15:00, 03/01/2013 16:00, 03/01/17:00)


Date        Time        Temperature
03/01/2013  13:00            75
03/01/2013  14:00            80
03/01/2013  15:00            82
03/01/2013  16:00            82
03/01/2013  17:00            81
03/01/2013  18:00            80

Its a weird use case and a bit diffult to put down on paper. Its an average of 3 hours, but every hour??

I would greatly appreciate any ideas on this.

4

2 回答 2

0

In SQL Server 2000, you would do this with a join. However, to make the joins easier and to dispense with the date arithmentic, I'm going to first define a join key.

select t1.date, t2.time, avg(t2.temperature) as avgTemp
from (select t.*,
             (select count(*) from t t2 where t2.date < t.date or t2.date = t.date and t2.time <= t.time
             ) as seqnum
      from t
     ) t1 left outer join
     (select t.*,
             (select count(*) from t t2 where t2.date < t.date or t2.date = t.date and t2.time <= t.time
             ) as seqnum
      from t
     ) t2
     on t.seqnum between t2.seqnum - 2 and t.seqnum
group by t1.date, t1.time

This is much easier in more recent versions of SQL Server (because they support window functions). You might consider upgrading.

于 2013-03-31T00:52:06.397 回答
0

Assuming Date and time fields are both varchars, below is what I got. (if they are not varchars, you will have to remove any unnecessary conversions I am doing below to get a datetime out of those two fields):

select t1.[Date],t1.[Time],Avg(t2.Temp)
from MyTable t1, MyTable t2
where
-- getting datetime out of date(varchar) and time(varchar) fields
dateadd(hh,(cast(left(t1.[Time],2),(convert(datetime,t1.[Date],101)))  
between
-- matching row from second table
dateadd(hh,(cast(left(t2.[Time],2),(convert(datetime,t2.[Date],101)))
and
-- matching row plus two hrs
dateadd(hh,2,dateadd(hh,(cast(left(t2.[Time],2),(convert(datetime,t2.[Date],101))))
group by t1.[Date],t1.[Time]

Not sure if there is a way without the join... I don't think so.

于 2013-03-31T01:20:48.833 回答