-1

我想列出不同范围内的用户点数

用户积分表结构

+---------------+--------------+------+-------------------+----------------+
| Field         | Type         | Null | Default           | Extra          |
+---------------+--------------+------+-------------------+----------------+
| ID            | int(11)      | NO   | NULL              | auto_increment |
| user_id       | int(11)      | NO   | NULL              |                |
| points        | int(11)      | NO   | NULL              |                |
+---------------+--------------+------+-------------------+----------------+

示例数据

+----------------------+
| ID    user_id points |
|----------------------|
| 1     14      5      |
| 2     15      10     |
| 3     5       14     |
| 4     3       20     |
| 5     14      10     |
| 6     15      17     |
| 7     5       61     |
| 8     14      81     |
| 9     15      12     |
| 10    3       47     |
| 11    15      10     |
| 12    14      17     |
| 13    3       27     |
| 14    5       18     |
| 15    3       4      |
+----------------------+

总点数(按用户分组)

+---------+---------------+
| user_id | total_points  |
+---------+---------------+
| 3       | 98            |
| 5       | 91            |
| 14      | 108           |
| 15      | 49            |
+---------+---------------+

首选输出

+--------+-------+
| Range  | Count |
+--------+-------+
| 0-50   | 01    |
| 50-100 | 02    |
| 100-150| 01    |
| > 150  | 00    |
+--------+-------+

我怎样才能在纯 mySQL 中实现该结果?

4

1 回答 1

2
SELECT 
   CASE
     WHEN points <= 50 THEN '0-50'
     WHEN points BETWEEN 51 AND 100 THEN '51-100'
     WHEN points BETWEEN 101 AND 150 THEN '101-150'
     ELSE '> 150'
   END AS `Range`
   ,COUNT(*) AS `Count`
   ,CASE
     WHEN points <= 50 THEN 1
     WHEN points BETWEEN 51 AND 100 THEN 2
     WHEN points BETWEEN 101 AND 150 THEN 3
     ELSE 4
   END AS `Sort`
FROM (
     SELECT user_id, SUM(points) as points
     FROM tbl
     GROUP BY user_id
     ) AS summary
GROUP BY `Range`, `Sort`
于 2013-10-15T11:20:14.540 回答