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

¿Cómo es mejor unir algunas tablas (incluidas las subconsultas) en una consulta?

Creo que esto te da lo que estás buscando (una de muchas maneras):

SELECT t.diapason, COUNT(*) AS 'number_of_users'
FROM (SELECT CASE  
    when amount<100 then '0-100' 
    when amount>=100 then '100 +' END AS diapason
    FROM 
        (SELECT SUM(amount) AS amount 
        FROM payments 
        INNER JOIN (SELECT DISTINCT user_id FROM activity where login_time between '2012-04-05' and '2012-04-12') AS a ON payments.user_id = a.user_id
        GROUP BY payments.user_id) AS P
      ) t
GROUP BY t.diapason
  ORDER BY number_of_users desc
;