订单
id | order_id | created_at | updated_at | total_amount |
---|---|---|---|---|
1 | abc123 | 2021-06-13 11:00:00 | 2021-06-13 11:00:00 | 230.5 |
2 | abc456 | 2021-06-01 07:00:00 | 2021-06-01 07:00:00 | 240 |
为了在过去 7 天与过去 7 天之前没有购买,我编写了以下查询
select
date_trunc('week', created_at) as "Week",
count(*) "No of purchases"
from orders
我如何才能在过去 14 天与过去 14 天之前没有购买?
有没有办法可以将“14 天”或类似的时间传递给 date_turnc
方法?
如果不是,我该如何编写此查询?
答案 0 :(得分:0)
为什么不直接使用日期比较?
select count(*) as num_purchases
from orders
where created_at >= current_date - interval '14 day'
答案 1 :(得分:0)
只需从 now()
(或任何其他为您提供当前时刻正确时间的函数/变量)中减去相应的时间间隔,并将其与创建时间戳进行比较。类似的东西:
SELECT count(*)
FROM orders
WHERE created_at >= now() - '14 days'::interval
AND created_at < now() - '7 days'::interval;