sql >> Base de Datos >  >> RDS >> Mysql

Usando SQL para encontrar el número total de clientes con más de X pedidos

Prueba esto:

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

Resultado:

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