简体   繁体   中英

Select accounts where last order placed was older than X date

I am trying to identify shoppers who last placed an order on or before a specific date. I want to do this so that I can identify stale accounts and unsubscribe them from mailings.

So far I have this query, but it seems to be retrieving accounts that have ordered more recently than the specified date - which is not what I want!

SELECT
  s.id,s.first_name,s.last_name,s.email, latest_orders.last_order_date, au.verified, au.unh
FROM
  (SELECT
     shopper_id, MAX(order_date) AS last_order_date
   FROM
     order_list WHERE order_date <= ?
   GROUP BY
     shopper_id) AS latest_orders
INNER JOIN
  shoppers s
ON
  s.id = latest_orders.shopper_id
JOIN auth_users au ON au.shopper_id=s.id 
  WHERE s.mail_outs='Y' LIMIT 50

Use having :

SELECT shopper_id, MAX(order_date) AS last_order_date
FROM order_list 
GROUP BY shopper_id
HAVING MAX(order_date) <= ?;

If you want all information about the shoppers, then join back to shoppers :

SELECT s.*, os.last_order_date
FROM shoppers s JOIN
     (SELECT shopper_id, MAX(order_date) AS last_order_date
      FROM order_list 
      GROUP BY shopper_id
      HAVING MAX(order_date) <= ?
     ) os
     ON os.shopper_id = s.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM