2016-12-05 86 views
0

以下查詢將時間戳分解爲日期forecast_day和小時forecast_hour將午夜時間戳重命名爲前一天的第24小時

我的問題是處理的2016-02-01 00:00:00時間戳返回先前的2016年1月31日一天的forecast_day和24.下面的代碼只是返回的2016年2月1日forecast_day和這樣一個時間戳0 forecast_hourforecast_hour

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) 
+0

23:59:59是一天的最後一秒。 24:00:00不存在。第二天0:00:00。這就是時間是如何被普遍認識的。如果您希望0:00:00表示前一天的最後一秒,那麼您需要使用if/case語句將0:00:00時間管理爲第1天。但爲什麼?!? 0:00:00是每天0-1秒!看起來你想要做的是在0:00:01開始新的一天,但到那時已經過去了整整一秒! – xQbert

+0

@xQbert好東西。謝謝(你的)信息。 – otterdog2000

回答

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,