mysqlsqlanalytical

Find the youngest customer with AT LEAST 1 purchase order


I need to write a query to find the youngest customer who bought atleast 1 product

Here is the data: CUSTOMER:

enter image description here

ORDER_DETAIL:

enter image description here

This is my query so far:

SELECT c.CUSTOMERID, c.age, c.name
from (
SELECT CUSTOMERID, COUNT(ORDERID) as "totalOrder"
FROM FACEBOOK_ORDER_DETAIL
GROUP BY CUSTOMERID 
HAVING COUNT(ORDERID) >=1) AS tbl
LEFT JOIN FACEBOOK_CUSTOMER c on c.CUSTOMERID = tbl.CUSTOMERID
order by c.age ;

However, above query gives me enter image description here

But I need the list of customers with the minimum age.


Solution

  • If you really only want a single youngest customer, even should there be a tie, then use LIMIT:

    SELECT c.CUSTOMERID, c.age, c.name
    FROM CUSTOMER c
    INNER JOIN FACEBOOK_ORDER_DETAIL o
        ON c.CUSTOMERID = c.CUSTOMERID
    ORDER BY
        c.age
    LIMIT 1;
    

    This should work because if a customer joins to the order details table, it implies that he had at least one order.

    If instead you want to find all youngest customers, including all ties, then a nice way to handle this uses the RANK analytic function:

    SELECT DISTINCT CUSTOMERID, age, name
    FROM
    (
        SELECT c.CUSTOMERID, c.age, c.name, RANK() OVER (ORDER BY c.age) rnk
        FROM CUSTOMER c
        INNER JOIN FACEBOOK_ORDER_DETAIL o
            ON c.CUSTOMERID = o.CUSTOMERID
    ) t
    WHERE rnk = 1;
    

    Demo

    For earlier versions of MySQL, we can use a subquery as a workaround for not having RANK:

    SELECT DISTINCT c.CUSTOMERID, c.age, c.name
    FROM CUSTOMER c
    INNER JOIN FACEBOOK_ORDER_DETAIL o
        ON c.CUSTOMERID = c.CUSTOMERID
    WHERE c.age = (SELECT MIN(t1.age)
                   FROM CUSTOMER t1
                   INNER JOIN FACEBOOK_ORDER_DETAIL t2
                       ON t1.CUSTOMERID = t2.CUSTOMERID);
    

    Demo