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

Consulta MySQL para agrupar datos en diferentes rangos

Debe crear una tabla en línea que contenga todos los rangos de precios. Luego realice un LEFT JOIN con una tabla derivada basada en su consulta para obtener el resultado esperado:

SELECT x.PriceRange, COALESCE(TotalWithinRange, 0) AS TotalWithinRange
FROM (
  SELECT "0 - 10" AS PriceRange 
  UNION SELECT "10 - 20"
  UNION SELECT "20 - 30"
  UNION SELECT "30 - 40"
  UNION SELECT "40 - 50"
  UNION SELECT "over 50" ) x
LEFT JOIN (  
   SELECT
      CASE when price >= 0 and price <= 10 then "0 - 10"
           when price > 10 and price <= 20 then "10 - 20"
           when price > 20 and price <= 30 then "20 - 30"
           when price > 30 and price <= 40 then "30 - 40"
           when price > 40 and price <= 50 then "40 - 50"
           else "over 50"
      END AS PriceRange,
      COUNT(*) as TotalWithinRange
   FROM YourTable
   GROUP BY 1 ) y ON x.PriceRange = y.PriceRange

Demostración de SQL Fiddle