假设我有一个表格,其中包含一个带时区的时间戳类型列。我们称之为 record_timestamptz 。我试图仅获取在一周中特定日期(或一周中连续两天)的给定时间片中具有 record_timestamptz 的记录。让我们假设我试图在星期三23:00到星期四03:00(UTC时间)之间获取所有记录。
我提出的查询不起作用:
SELECT *
FROM TABLE
WHERE (
EXTRACT (DOW FROM record_timestamptz::timestamp AT TIME ZONE 'UTC') =
EXTRACT (DOW FROM TIMESTAMP '2016-02-03 23:00:00+00')
AND
record_timestamptz::time AT TIME ZONE 'UTC' >= '23:00:00'::time AT TIME ZONE 'UTC')
OR
(EXTRACT (DOW FROM record_timestamptz::timestamp AT TIME ZONE 'UTC') =
EXTRACT (DOW FROM TIMESTAMP '2016-02-04 03:00:00+00')
AND
record_timestamptz::time AT TIME ZONE 'UTC' <= '03:00:00'::time AT TIME ZONE 'UTC'
)
ORDER BY record_timestamptz DESC
问题在于&#34;在时区&#39; UTC&#39;&#34;在任何一方都没有做任何事情。查询的输出给出了&#34; 23:00:00-2&#34;和&#34; 03:00:00-2&#34;而不是&#34; 21:00:00 + 00&#34;和&#34; 01:00:00 + 00&#34;,假设数据库中的所有记录的时区偏移为-2。
答案 0 :(得分:1)
select *, record_timestamptz at time zone 'utc'
from
t
right outer join
(
select tstzrange(d, d + interval '6 hours') as r
from generate_series (
'2016-01-27 21:00:00+00'::timestamptz, '2016-03-31', '7 day'
) gs (d)
) gs on record_timestamptz <@ gs.r
order by gs.r desc