mySQL - 用户的总积分计数在动态范围的不同范围内

时间:2013-10-25 06:14:15

标签: mysql fetch

当我尝试执行以下查询时,它会给我正确的结果,但我想动态显示范围

 SELECT
 CASE
 WHEN points <= 25 THEN '0-25'
 WHEN points BETWEEN 25 AND 50 THEN '25-50'
 WHEN points BETWEEN 50 AND 75 THEN '50-75'
 WHEN points BETWEEN 75 AND 100 THEN '75-100'
 ELSE '> 100'
 END AS `Range`
 ,COUNT(*) AS `Count`
 ,CASE
 WHEN points <= 25 THEN 1
 WHEN points BETWEEN 25 AND 50 THEN 2
 WHEN points BETWEEN 50 AND 75 THEN 3
 WHEN points BETWEEN 75 AND 100 THEN 4
 ELSE 5
 END AS `Sort`
 FROM (
 SELECT user_id, SUM(points) as points
 FROM tbl
 GROUP BY user_id
 ) AS summary
 GROUP BY `Range`, `Sort`

输出

+--------+-------+
| Range  | Count |
+--------+-------+
| 0-20   | 01    |
| 25-50  | 02    |
| 50-75  | 01    |
| 75-100 | 04    |
| > 100  | 00    |
+--------+-------+

我从另一个表中的跟随值获得100值

SELECT MIN(points)FROM tbl1 where 1 LIMIT 0,1

如果最小值为100,则输出为:

输出

+--------+-------+
| Range  | Count |
+--------+-------+
| 0-20   | 01    |
| 25-50  | 02    |
| 50-75  | 01    |
| 75-100 | 04    |
| > 100  | 00    |
+--------+-------+

如果最小值为500,则输出为:

输出

+---------+-------+
| Range   | Count |
+---------+-------+
| 0-100   | 01    |
| 100-200 | 02    |
| 300-400 | 01    |
| 400-500 | 04    |
| > 500   | 00    |
+---------+-------+

提前致谢

1 个答案:

答案 0 :(得分:1)

SELECT CASE WHEN points <= range1 THEN CONCAT('0-', range1)
            WHEN points <= range2 THEN CONCAT(range1, '-', range2)
            WHEN points <= range3 THEN CONCAT(range2, '-', range3)
            WHEN points <= range4 THEN CONCAT(range3, '-', range4)
            ELSE CONCAT('> ', range4)
       END AS `Range`
       ,COUNT(*) AS `Count`
       ,LEAST(5, GREATEST(1, CEIL(points/range1))) AS Sort
FROM (SELECT user_id, SUM(points) as points
      FROM tbl
      GROUP BY user_id
     ) AS summary
JOIN (SELECT FLOOR(MIN(points)*.25) range1, FLOOR(MIN(points)*.50) range2, FLOOR(MIN(points)*.75) range3, MIN(points) range4 FROM tbl1) x
GROUP BY `Range`, `Sort`

请注意,您不需要在BETWEEN子句中使用WHEN。这些子句按顺序进行测试,因此如果它超过points <= 25,则必须大于25,并且没有必要在下一个子句中明确地测试它。