1

Hi I have a weather database in SQL Server 2008 that is filled with weather observations that are taken every 20 minutes. I want to get the weather records for each hour not every 20 minutes how can I filter out some the results so only the first observation for each hour is in the results.

Example:

7:00:00
7:20:00
7:40:00
8:00:00

Desired Output

7:00:00 
8:00:00
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
GarrettH
  • 29
  • 1
  • 7

5 Answers5

1

To get exactly (less the fact that it's an INT instead of a TIME; nothing hard to fix) what you listed as your desired result,

SELECT DISTINCT DATEPART(HOUR, TimeStamp)
FROM Observations

You could also add in CAST(TimeStamp AS DATE) if you wanted that as well.


Assuming you want the data as well, however, it depends a little, but from exactly what you've described, the simple solution is just to say:

SELECT *
FROM Observations
WHERE DATEPART(MINUTE, TimeStamp) = 0

That fails if you have missing data, though, which is pretty common.


If you do have some hours where you want data but don't have a row at :00, you could do something like this:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY CAST(TimeStamp AS DATE), DATEPART(HOUR, TimeStamp) ORDER BY TimeStamp)
    FROM Observations
)

SELECT *
FROM cte
WHERE n = 1

That'll take the first one for any date/hour combination.

Of course, you're still leaving out anything where you had no data for an entire hour. That would require a numbers table, if you even want to return those instances.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
0

You can use a formula like the following one to get the nearest hour of a time point (in this case it's GETUTCDATE()).

SELECT  DATEADD(MINUTE, DATEDIFF(MINUTE, 0, GETUTCDATE()) / 60 * 60, 0)

Then you can use this formula in the WHERE clause of your SQL query to get the data you want.

Just a learner
  • 26,690
  • 50
  • 155
  • 234
0

What you need is to GROUP BY your desired time frame, like the date and the hours. Then, you get the MIN value of the timeframe. Since you didn't specify which columns you are using, this is the most generic thing i can give.

stb
  • 3,405
  • 2
  • 17
  • 24
0

Use as filter :

... where DATEPART(MINUTE, DateColumn) = 0
Didier68
  • 1,027
  • 12
  • 26
0

To filter the result for every whole hour, you can set your where clause to check for 00 minute since every whole hour is HH:00:00.

To get the minute part from a time-stamp, you can use DATEPART function.

SELECT * 
FROM YOURTABLENAME
WHERE DATEPART(MINUTE, YOURDATEFIELDNAME) = 0

More information on datepart function can be found here: http://www.w3schools.com/sql/func_datepart.asp

NKD
  • 1,039
  • 1
  • 13
  • 24