SELECT *
FROM Conference WHERE date_start ---don't know how to proceed---
如何查看上个月是否有date_start
?谢谢你。
答案 0 :(得分:17)
从当月减去一个月,然后将其“截断”到该日期的开头。由于您不想包含“this”月份的行,您还需要为该
添加条件SELECT *
FROM Conference
WHERE date_start >= date_trunc('month', current_date - interval '1' month)
and date_start < date_trunc('month', current_date)
date_trunc('month', current_date - interval '1' month)
将返回上个月的第一天,date_trunc('month', current_date)
将返回“此”月的第一天。
答案 1 :(得分:1)
SELECT * FROM Conference WHERE date_trunc('month', date_start)=
date_trunc('month', current_date - interval '1' month)
注意时区
date_trunc('month', (date_start at time zone 'UTC'))
此外,您可以添加索引以使其更快
CREATE OR REPLACE FUNCTION fn_my_date_trunc(period text,
some_time timestamp with time zone)
RETURNS timestamp with time zone
AS
$BODY$
select date_trunc($1, $2);
$BODY$
LANGUAGE sql
IMMUTABLE;
CREATE INDEX "IdxConferenceDateStart" ON Conference
(fn_my_date_trunc('month', (date_start at time zone 'UTC')));
是的,当然,您必须在请求中使用声明的函数'fn_my_date_trunc'才能自动使用此索引(并将日期时间转换为时区日期时间)