返回购买日期在注册日期后7天内的所有结果



到目前为止,我已经生成了以下代码,试图将相关数据汇总在一起。

然而,使用"+7"函数会产生以下问题。

Registration date = '2018-01-01'

它正在撤回2018-04-08的购买日期,即只要当天的日期比它大7天,就被认为是可以接受的。事实上,我想要的是在注册日期后7天内购买的任何商品。

如有任何建议/帮助,我们将不胜感激。

select *
from purchases b
inner join registrations r
on r.customer_id = b.customer_id
and day(b.purchase_date) between d(r.account_opening_date) and day(r.account_opening_date) + 7
and r.account_opening_date >= '2018-01-01 00:00:00.0'

如果要比较的日期在不同的月份,请改用DATE_ADD,DAY((将无法正常工作。

AND b.purchase_date >= r.account_opening_date AND 
b.purchase_date <= DATE_ADD(r.account_opening_date INTERVAL 7 Day)

您可以使用窗口函数

select *
partition by (order by account_opening_date rows 6 preceding)
from purchases p, registrations r
where p.customer_id = r.customer_id
and r.account_opening_date >= '2018-01-01 00:00:00.0'

您可以简单地使用+:

select *
from purchases b inner join
registrations r
on r.customer_id = b.customer_id and
b.purchase_date >= r.account_opening_date and 
b.purchase_date < r.account_opening_date + interval 7 day
where r.account_opening_date >= '2018-01-01';

如果要在没有时间组件的情况下执行此操作,请使用date()函数:

on r.customer_id = b.customer_id and
b.purchase_date >= r.account_opening_date and 
b.purchase_date <= date(r.account_opening_date) + interval 7 day
where r.account_opening_date >= '2018-01-01'

使用<还是<=取决于对"7天内"的准确解释。这个版本假设你真的想要7-8天。

听起来您需要使用DATE_ADD和DATEMySQL函数。

select *
from purchases b
inner join registrations r
on r.customer_id = b.customer_id
and date(b.purchase_date) between date(r.account_opening_date) and date_add(r.account_opening_date interval 7 day)
and r.account_opening_date >= '2018-01-01 00:00:00.0'

最新更新