Mysql
 sql >> Database >  >> RDS >> Mysql

Utilizzo di SQL per trovare il numero totale di clienti con oltre X ordini

Prova questo:

SELECT T1.products_bought, COUNT(T2.cnt) AS total
FROM (
    SELECT '<5' AS products_bought, 0 AS a, 4 AS b
    UNION ALL
    SELECT '5-10', 5, 10
    UNION ALL
    SELECT '>10', 11, 999999
) T1
LEFT JOIN
(
    SELECT COUNT(DISTINCT ProductID) AS cnt
    FROM ORDERS
    GROUP BY CustomerID
) T2
ON T2.cnt BETWEEN T1.a AND T1.b
GROUP BY a, b

Risultato:

products_bought  total
<5               3    
5-10             0    
>10              0