将午夜时间戳重命名为前一天的第24小时

时间:2016-12-05 21:04:47

标签: sql postgresql case

以下查询将时间戳分解为日期forecast_day和小时forecast_hour

我的问题是处理2016-02-01 00:00:00的时间戳,以返回前一天2016-01-31的forecast_dayforecast_hour的24。下面的代码只返回forecast_day对于这样的时间戳,2016-02-01和forecast_hour为0。

select
  a.lat, a.lon,
  date_trunc('day', a.foretime - interval '5 hours')::date as forecast_day,
  extract(hour from a.foretime - interval '5 hours') as forecast_hour,
  f.windspeed as forecast,
  a.as_of - interval '5 hours' as latest_as_of
from weather.forecast f
  join (select
          foretime,
          max(as_of) as as_of,
          lat, lon
        from weather.forecast
        where date_trunc('day', foretime - interval '5 hours')::date - as_of >= interval '9 hours'
        group by foretime, lat, lon) a using (foretime, as_of, lat, lon)

1 个答案:

答案 0 :(得分:2)

您将使用case。 。 。或技巧:

select . . .
       (case when extract(hour from a.foretime - interval '5 hours') = 0 
             then date_trunc('day', a.foretime - interval '5 hours')::date - interval '1' day
             else date_trunc('day', a.foretime - interval '5 hours')::date
        end) as forecast_day,
       (case when extract(hour from a.foretime - interval '5 hours') = 0
             then 24
             else extract(hour from a.foretime - interval '5 hours')
        end) as forecast_hour,