Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is Today the Customer's First Order Anniversary?

I’m trying to get a MySQL query working to see if today is a customer’s first order date. I’m looking at a single database table – tblOrders

My attempt so far, leads to orders returned that happened to fall on today’s date at some point, but is not their ‘first’ order.

SELECT FirstName, LastName, Email, COUNT(OrderID) AS NumberOfOrders, CreateDate
FROM tblOrders
WHERE (MONTH(CreateDate) = MONTH(NOW()) 
    AND DAY(CreateDate) = DAY(NOW()))
GROUP BY Email
ORDER BY CreateDate

I feel like I’m needing a subquery, but I’m spinning my wheels.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want the customer’s first order, you’d need to use MIN(CreateDate), but aggregates cannot appear in the WHERE they must appear in the HAVING, so your query would be:

SELECT  o.FirstName, 
        o.LastName, 
        o.Email, 
        COUNT(o.OrderID) AS NumberOfOrders, 
        MIN(o.CreateDate) AS FirstOrder
FROM    tblOrders AS o
GROUP BY o.FirstName, o.LastName, o.Email
HAVING  MONTH(MIN(o.CreateDate)) = MONTH(NOW()) 
AND     DAY(MIN(o.CreateDate)) = DAY(NOW());

Your issue here though is that your count will be only counting orders on the same month/day as today, and not all the orders ever for that customer, so if you only want to know the customer details this is fine, but if you need the total number of orders for this customer you’ll need a subquery (as you thought):

SELECT o.FirstName, o.LastName, o.Email, o.NumberOfOrders, o.FirstOrder
FROM  ( 
        SELECT o.FirstName, 
               o.LastName, 
               o.Email,
               MIN(o.CreateDate) AS FirstOrder,
               COUNT(*) AS NumberOfOrders
        FROM   tblOrders AS o
        GROUP BY o.FirstName, o.LastName, o.Email
      ) AS o
WHERE MONTH(o.FirstOrder) = MONTH(NOW())
AND   DAY(o.FirstOrder) = DAY(NOW());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading