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

eqfvzcg8  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(338)

到目前为止,我已经生成了下面的代码来尝试将相关数据拉到一起。
但是,“+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'
gstyhher

gstyhher1#

你可以使用窗口功能

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'
x7rlezfr

x7rlezfr2#

如果要比较的日期在不同的月份,则改用date\u add,day()将无法正常工作。

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

hiz5n14c3#

你可以简单地使用 + :

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天。

zf9nrax1

zf9nrax14#

听起来您需要使用date\u add和date mysql函数。

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'

相关问题