Sunday, 15 February 2015

mysql - SQL Group By Number Of Users Within Range -


I have the following questions that will return the number of users in the table transaction earned between $ 100 and $ 200

  Exclude users from SELECT COUNT (users.id) transactions transactions on users.id = transactions.user_id.Understanding & gt; 100 more transactions Amount & lt; 200   

The above query returns the correct result below:

  COUNT (users.id) 559   

I So that the query can return the data in the following format:

  COUNT (users.id): amount 1678: 0-100 55 9: 100-200 13: 200-300   

How can I do this?

You can use the case expression inside your overall function that will result in columns:

  SELECT COUNT (when zodiac = 0 and zodiac = lt; = 100 and users.id end) Amt0_100, COUNT (case when zodiac => 101 = amount & lt; = 200 then users .id end) Amt101_200, COUNT (in case when the amount> = 201 and the sum & lt; = 300 then users.id end) Users join except for Amt201_300 transactions User.id = transaction.user_id;   

I'll change the range from 0-100, 101-200, 201-300, otherwise you will be counting the user ID twice, 200 values ​​ < P> If you want values ​​in rows, you can use it:

  select count (u.id), in case when the amount is & gt; = 0 more amount & lt; = 100 Then '0-100' WHEN Amount & gt; = 101 and Amount & lt; = 200 THEN '101-200' WHEN Zodiac & gt; = 201 and Amount & lt; = 300 THEN '101-300' END to join the amount in the left U.D. = TUSR_ID group when user U.A.I. by amount & gt; = 0 more amount & lt; = 100 THEN '0-100' WHEN Amount & gt; = 101 and Amount & lt; = 200 THEN '101-200' WHEN Zodiac & gt; = 201 and Amount & lt; See = 300 THEN '101-300' END   

But if you have many categories, then you need to calculate calculations but then you have to You might want to consider creating a table with the same category of:

  Create a table report_order (start_range int, end_range int); Enter Report_range values ​​(0, 100), (101, 200), (201, 300);   

Then you can use to connect to the category values ​​in your existing tables and set the table:

  select count (u.id) leave total, concat (Start_range, '-', end_range) Ukaidi = left Uodiu UID amount of transactions Tikyuesaraiaiaidi report RR RR Tikmount & gt; = R.start_range and t.amount & lt; = Concat (start_range, '-', and_range) by r.end_range group;   

If you want to create a new table with borders, you can always use the derived table to get the same results:

  select count (u.id) Total Contact (start_range, '-', end_range) select Join amount of transactions left Uoai Uaiaidi = t.user_id (0 start_range, 100 And_renj union all select 101 Start_reng 200 And_renj Union, all selected 201 Start_reng , 300 End_Range) T. mount on RT & gt; = R.start_range and t.amount & lt; = Concend by r.end_range group (start_range, '-', end_range);   

View

No comments:

Post a Comment