您完全无需CASE 即可获得所需的内容。
要意识到的一件事是,当使用日期/时间戳转换为文本时几乎总是不必要和不正确的(就像这里的情况一样)基本上只是不这样做。使用Postgres date functions。
以下给出了您想要的。它开始创建一个 CTE 来定义时间段和每个时间段的描述性名称。然后它将该 CTE 与飞行表连接起来。 (见演示here)
with departures( stime, etime, description) as
(values ('00:00:00'::time, '02:00:00'::time, 'Night flight')
, ('02:00:00'::time, '06:00:00'::time, 'Early morning flight')
, ('06:00:00'::time, '11:00:00'::time, 'Morning flight')
, ('11:00:00'::time, '16:00:00'::time, 'Noon flight')
, ('16:00:00'::time, '19:00:00'::time, 'Evening flight')
, ('19:00:00'::time, '24:00:00'::time, 'Night flight')
)
select f.flight_id "Flight Id"
, (f.departure at time zone 'Asia/Kolkata')::time(0) "Schedule Departure Time"
, d.description "Description"
from departures d
join flights f
on ( (f.departure at time zone 'Asia/Kolkata')::time(0) >= d.stime
and (f.departure at time zone 'Asia/Kolkata')::time(0) < d.etime
)
order by "Schedule Departure Time";
注意事项:
- 时间戳始终包含日期和小数秒。自从你
想要只是时间比较都需要被丢弃。这是
使用
::time(0) 完成。但是,它确实会四舍五入到最接近的
第二。
- 我更改了您对“夜间飞行”的定义。在时间戳中,之后
丢弃日期得到的时间,
23:00:00 将总是
大于02:00:00。更改纠正了这一点。
- 我使用 “亚洲/加尔各答”时区来获得 +3.5 小时
从 UTC 偏移(在 UTC-5 时)。取决于您的服务器时区
设置你可能不需要这个。
我是新手,如果格式不规范,请多多包涵。
所以我在写完这段代码后得到了预期的输出......
'''
with flights ( stime, etime, description) as
(values ('00:00:00'::time, '02:00:00'::time, 'Night flight')
, ('02:00:00'::time, '06:00:00'::time, 'Early morning flight')
, ('06:00:00'::time, '11:00:00'::time, 'Morning flight')
, ('11:00:00'::time, '16:00:00'::time, 'Noon flight')
, ('16:00:00'::time, '19:00:00'::time, 'Evening flight')
, ('19:00:00'::time, '24:00:00'::time, 'Night flight')
)
select flight_id "Filght ID"
, flight_no "Flight No"
, scheduled_departure "scheduled_departure"
, scheduled_arrival "scheduled_arrival"
, flights "Timings"
from flights
join bookings.flights f
on ( (scheduled_departure at time zone 'Asia/Kolkata')::time(0) >= stime
and (scheduled_arrival at time zone 'Asia/Kolkata')::time(0) < time
)
'''
但在修改后的列中,我只想要诸如“夜间飞行”之类的文本,而不是“00:00:00”::time、“02:00:00”::time、“夜间飞行”的整个时间
我怎样才能得到文本输出?
第二次我尝试使用havin'或where语句过滤输出
使用此代码
with flights ( stime, etime, description) as
(values ('00:00:00'::time, '02:00:00'::time, 'Night flight')
, ('02:00:00'::time, '06:00:00'::time, 'Early morning flight')
, ('06:00:00'::time, '11:00:00'::time, 'Morning flight')
, ('11:00:00'::time, '16:00:00'::time, 'Noon flight')
, ('16:00:00'::time, '19:00:00'::time, 'Evening flight')
, ('19:00:00'::time, '24:00:00'::time, 'Night flight')
)
select flight_id "Filght ID"
, flight_no "Flight No"
, scheduled_departure "scheduled_departure"
, scheduled_arrival "scheduled_arrival"
, flights "Timings"
from flights
join bookings.flights f
on ( (scheduled_departure at time zone 'Asia/Kolkata')::time(0) >= stime
and (scheduled_arrival at time zone 'Asia/Kolkata')::time(0) < etime
)
group by
flight_id,
flights
having flights = 'Morning flight'
这样说给我一个错误
错误:未实现匿名复合类型的输入
第 22 行:有航班 = '早上的航班'
(粘贴文本,因为我的帐户中允许使用图片)
@belayer