如果我要查看一个月前10天的数据,又如何查看上个月前10天的数据?
我本质上是想确切地了解前一个月发生了什么(但是目前我在当月的时间长短)。
示例:
现在是10/11,我正在查看十月的数据。我会看到从10/1到10/11的所有内容。
然后我也想看看从9/1到9/11的数据是什么样的
我会使用Interval和/或“ date_trunc”功能吗?
答案 0 :(得分:0)
是的,您可以使用date_trunc到达月初,也可以减去1个月的间隔来获得上个月:
PG::UndefinedColumn: ERROR: column courses.user_id does not exist
LINE 1: SELECT 1 AS one FROM "courses" WHERE "courses"."user_id" = ...
^
: SELECT 1 AS one FROM "courses" WHERE "courses"."user_id" = $1 AND "courses"."course_id" = $2 LIMIT $3
答案 1 :(得分:0)
这是我“入侵”它的方式:
select x.now, count(x.status) as total
from
(
select now(), date_trunc('month', now()) as start_of_month, now() -
interval '1 month' as last_month
, date_trunc('month', now() - interval '1 month') as
start_of_last_month, status
, created_date
from my_table
)x
where x.created_date between x.start_of_month and x.now
group by x.now
UNION ALL
select x.last_month, count(x.status) as total
from
(
select now(), date_trunc('month', now()) as start_of_month, now() -
interval '1 month' as last_month
, date_trunc('month', now() - interval '1 month') as
start_of_last_month, status
, created_date
from my_table
)x
where x.created_date between x.start_of_last_month and x.last_month
group by x.last_month
使用“ UNION ALL” ,我在select和where子句中将“ x.now” 替换为“ x.last_month” 日期时间范围,所以现在我有了当前月份(无论我在哪个月份),上个月也有相同的事情