MySQL query help needed to get clients who haven't bought anything in more than 180 days!
I have a table Orders which stores the info about orders(including OrdersName,OrdersSurname,OrdersEmail,OrdersPhone) which is the info I need to get.
It contains a field OrdersFinishedTime which is a DateTime field which stores the data when the order was finished.
What I need to do is select OrdersName,OrdersSurname,OrdersEmail,OrdersPhone from the Orders table for users who haven't bought anything in more than 180 days.
That is - I need to find unique users who's LAST UNIQUE purchase was more than 180 days ago.
Thanks in advance!
EDIT:
I know how to find all the records order than 180 days, but I need records which are 180 days older and there are no more orders(for that part开发者_C百科icular user) after that date!
EDIT2: you probably are not reading the question through. I need to find unique users who haven't purchased anything in more than 180 days. I don't need orders older than 180 days, I need the user info which is stored in the orders.
my current SQL query is like this:
SELECT DISTINCT O.OrdersEmail
,O.OrdersName
,O.OrdersSurname
,O.OrdersPhone
,O.OrdersFinishedTime
FROM (SELECT OrdersPhone
, MAX(OrdersFinishedTime
) AS OrdersFinishedTime
FROM Orders
WHERE YEAR(OrdersFinishedTime
) >= 2010 GROUP BY OrdersPhone
HAVING DATEDIFF(NOW(),MAX(OrdersFinishedTime
)) >= 180) AS LastOrders
INNER JOIN Orders
AS O USING(OrdersPhone
,OrdersFinishedTime
) ORDER BY OrdersFinishedTime
DESC
try this:
SELECT `OrdersName`, `OrdersSurname`, `OrdersEmail`, `OrdersPhone` FROM `Orders ` WHERE `OrdersFinishedTime` < SUBDATE(NOW(), 180);
SELECT * FROM Orders WHERE OrdersFinishedTime < DATE_SUB(NOW(), INTERVAL 180 DAY)
SELECT OrdersName,OrdersSurname,OrdersEmail,OrdersPhone from Orders
WHERE TO_DAYS(NOW()) - TO_DAYS(OrdersFinishedTime) > 180
ORDER BY OrdersFinishedTime DESC
LIMIT 1;
Last order which is more than 180 days ago.
Surely something like the following would do the trick.:
SELECT DISTINCT OrdersName,OrdersSurname,OrdersEmail,OrdersPhone FROM Orders
WHERE OrdersID IN
(SELECT OrdersID FROM Orders
WHERE OrdersFinishedTime < (NOW() - INTERVAL 180 DAY))
精彩评论