我这个查询返回从当前日期起 30 天的数据,需要修改它以仅返回当前月份的数据,而不是从当前日期起 30 天
SELECT count(1) AS counter FROM users.logged WHERE createddate >= date_trunc('month', CURRENT_DATE);
基于 Postgres 如何调整此查询的任何提示
问候
我这个查询返回从当前日期起 30 天的数据,需要修改它以仅返回当前月份的数据,而不是从当前日期起 30 天
SELECT count(1) AS counter FROM users.logged WHERE createddate >= date_trunc('month', CURRENT_DATE);
基于 Postgres 如何调整此查询的任何提示
问候
像这样的东西应该工作。
SELECT count(1) AS counter
FROM users.logged
WHERE date_trunc('month', createddate) = date_trunc('month', current_date);
它已经应该返回当月的值。截断进行转换10 Nov 2013 14:16 -> 01 Nov 2013 00:00
,它将返回本月初以来的数据。问题似乎是别的。
Ive this query which return data for 30 days from current date , need to modify it to return data for current month only not 30 days from current date
That's incorrect. Your query:
SELECT count(1) AS counter FROM users.logged WHERE createddate >= date_trunc('month', CURRENT_DATE);
returns all dates >= Nov 1st 00:00:00, in other words what you say that you want already. Or then, you've simplified your query and left out the more important bits — those that are broken. If not:
It might be that you've dates in the future and that you're getting incorrect counts as a result. If so, add an additional criteria in the where clause:
AND created_date < date_trunc('month', CURRENT_DATE) + interval '1 month'
It might also be that your sample data has a bizarre row with a time zone such that it looks like the timestamp is from this month but the date/time arithmetics land it last month.
这只会为您提供当月的数据。我尝试提取month
和year
. 最后一步是您可以将创建日期与当前日期时间进行比较。
SELECT count(1) AS counter
FROM users.logged
WHERE
EXTRACT(MONTH FROM createddate) = EXTRACT(MONTH FROM current_date)
AND EXTRACT(YEAR FROM createddate) = EXTRACT(YEAR FROM current_date);