Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

mysql - How it is better to join a few tables (including subqueries) in one query?

How it is better to join a few tables (including suqueries) in one query?

For example, I've got 2 tables: activity (user_id, login_time) and payments (user_id, payment_time, amount). Both tables conclude duplicate id's.

The task is to select unique user_id, which ever payed, with login_time from 05.04.12 until 10.04.12. Then range the by group accotding of total amount.

My query is:

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 GROUP BY payments.user_id) p) t
  GROUP BY t.diapason
  ORDER BY number_of_users desc;

I dont know where should I use 'inner join a....between '2012-04-05' and'2012-04-10''

Please help, thanks!

DATA SAMPLE

activity
user_id    login_time
1          05.04.2012
2          05.04.2012
3          06.04.2012
4          30.05.2012

payments
user_id    amount   payment_time
1          50       10.12.2011
1          20        09.12.2011
2          400        08.08.2011

Output for period 05.04.2012-10.04.2012

diapason     number_of_users
0-100          2
100+           1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe this gets you what you're looking for (one of many ways):

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
;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...