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

Come è meglio unire alcune tabelle (comprese le sottoquery) in una query?

Credo che questo ti dia ciò che stai cercando (uno dei tanti modi):

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
;