mysql How to find data in SQL in which you have to find out records which exist before last 30 days but not in last 30 days

68bkxrlz  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(124)

How do you use current date function in it?
I have been trying to use current date function. We need to find out customer_id who have not ordered in last 30 days but have ordered previously in MySQL, biq query

o7jaxewo

o7jaxewo1#

It's unclear if you care about the exact time.
If it's enough to just go 30 days back, we can simply use GROUP BY with a HAVING clause.
We say the latest order date of the customer_id must be before todays's date - 30 days:

SELECT customer_id
FROM yourtable
GROUP BY customer_id
HAVING MAX(orderDate) < NOW() - INTERVAL 30 DAY
ORDER BY customer_id;

What did I mean by "care about the time"? Well, the above query would select an id if for example the latest date of this id was only 30 days ago and mot more, but the time was before the current time, because in this case, the time difference would be less than 31 days, but exceed 30 days.
So if we only want to consider the day and ignore the time, we can extend this query like this:

SELECT customer_id
FROM yourtable
GROUP BY customer_id
HAVING MAX(CAST(orderDate AS DATE)) < 
CURDATE() - INTERVAL 30 DAY
ORDER BY customer_id;

Thus, the times will be truncated, i.e. "ignored".
We can see here this is working and can replicate the difference between the two queries: db<>fiddle
Note this answer assumes you are using a MYSQL DB because you wrote this in your question. I don't know what you mean by "big query".

相关问题