postgres sql - generate_series for date - 如何在日期上做一个 WHERE 条件(有时区)
postgres sql - generate_series for date - how to do a WHERE condition on the date (has timezone)
我在下面的 generate_series 个日期上有一个 postgres SQL 查询(带有时区,因为我希望它是特定时区的),我想放置一个 WHERE 条件以根据条件进行过滤在特定日期。我尝试使用以下 WHERE 语句但失败了。
where d::date = "2020-11-21"
您也可以在这里测试我的查询 - https://dbfiddle.uk/?rdbms=postgres_13&fiddle=b62dcd5f867a352645c0b2944a32a010
SELECT
d::date AT TIME ZONE 'Asia/Tokyo' AS created_date,
e.id,
e.name,
e.division_id,
MIN(a.created_at) FILTER (WHERE a.activity_type = 1) as min_time_in,
MAX(a.created_at) FILTER (WHERE a.activity_type = 2) as max_time_out
FROM (SELECT MIN(created_at), MAX(created_at) FROM attendance) AS r(startdate,enddate)
, generate_series(
startdate::timestamp,
enddate::timestamp,
interval '1 day') g(d)
CROSS JOIN employee e
LEFT JOIN attendance a ON a.created_at::date = d::date AND e.id = a.employee_id
where d::date = "2020-11-21" <--- this is an error, how do I query on a specific date
GROUP BY
created_date
, e.id
, e.name
, e.division_id
ORDER BY
created_date
, e.id;
它抱怨:
ERROR: column "2020-11-21" does not exist
LINE 15: where d::date = "2020-11-21"
双引号代表标识符,而你想要的是文字日期。您可以使用标准文字日期来表达这一点:
where d::date = date '2020-11-21'
或使用 Postgres 转换:
where d::date = '2020-11-21'::date
如果d
没有时间成分,则不需要转换:
where d = date '2020-11-21'
如果发生这种情况,您仍然可以使用半开过滤器避免强制转换:
where d >= date '2020-11-21' and d < date '2020-11-21' + interval '1 day'
我在下面的 generate_series 个日期上有一个 postgres SQL 查询(带有时区,因为我希望它是特定时区的),我想放置一个 WHERE 条件以根据条件进行过滤在特定日期。我尝试使用以下 WHERE 语句但失败了。
where d::date = "2020-11-21"
您也可以在这里测试我的查询 - https://dbfiddle.uk/?rdbms=postgres_13&fiddle=b62dcd5f867a352645c0b2944a32a010
SELECT
d::date AT TIME ZONE 'Asia/Tokyo' AS created_date,
e.id,
e.name,
e.division_id,
MIN(a.created_at) FILTER (WHERE a.activity_type = 1) as min_time_in,
MAX(a.created_at) FILTER (WHERE a.activity_type = 2) as max_time_out
FROM (SELECT MIN(created_at), MAX(created_at) FROM attendance) AS r(startdate,enddate)
, generate_series(
startdate::timestamp,
enddate::timestamp,
interval '1 day') g(d)
CROSS JOIN employee e
LEFT JOIN attendance a ON a.created_at::date = d::date AND e.id = a.employee_id
where d::date = "2020-11-21" <--- this is an error, how do I query on a specific date
GROUP BY
created_date
, e.id
, e.name
, e.division_id
ORDER BY
created_date
, e.id;
它抱怨:
ERROR: column "2020-11-21" does not exist
LINE 15: where d::date = "2020-11-21"
双引号代表标识符,而你想要的是文字日期。您可以使用标准文字日期来表达这一点:
where d::date = date '2020-11-21'
或使用 Postgres 转换:
where d::date = '2020-11-21'::date
如果d
没有时间成分,则不需要转换:
where d = date '2020-11-21'
如果发生这种情况,您仍然可以使用半开过滤器避免强制转换:
where d >= date '2020-11-21' and d < date '2020-11-21' + interval '1 day'