我正在寻找一种将MYSql数据分组为存储桶(值范围)的方法,然后计算每个组中有多少个值,然后将其绘制到一个图上。
我有很多的范围,不是很少像这里,我会做手动。
例如,如果我的数据看起来是:
+--------+
| column |
+--------+
| 1 |
| 2 |
| 10 |
| 15 |
| 20 |
| 100 |
| 150 |
| 1000 |
| 10000 |
+--------+我可以创建桶并计算每个桶中的值数:
+-------------+---------------+-----------------+-----------------+
| bucket(0-9) | bucket(10-99) | bucket(100-999) | bucket(1000-1M) |
+-------------+---------------+-----------------+-----------------+
| 2 | 3 | 2 | 2 |
+-------------+---------------+-----------------+-----------------+发布于 2017-09-27 12:21:59
如果上限小于1M,也许您可以根据您的样本数据和期望的结果尝试count(case when ... then .. end):
select
count(case when col between 0 and 9 then 1 end) `bucket(0-9)`,
count(case when col between 10 and 99 then 1 end) `bucket(10-99)`,
count(case when col between 100 and 999 then 1 end) `bucket(100-999)`,
count(case when col between 1000 and 1000000 then 1 end) `bucket(1000-1M)`
from test检查演示 in SQLFiddle。
发布于 2017-09-27 12:35:00
这是另一个玩法..。
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (i INT NOT NULL PRIMARY KEY);
INSERT INTO my_table VALUES
(1),
(2),
(10),
(15),
(20),
(100),
(150),
(1000),
(10000);
SELECT LENGTH(i) bucket
, CONCAT(RPAD(1,LENGTH(i),0),'-',RPAD(9,LENGTH(i),9)) range
, COUNT(*) total
FROM my_table
GROUP
BY bucket;
+--------+-------------+-------+
| bucket | range | total |
+--------+-------------+-------+
| 1 | 1-9 | 2 |
| 2 | 10-99 | 3 |
| 3 | 100-999 | 2 |
| 4 | 1000-9999 | 1 |
| 5 | 10000-99999 | 1 |
+--------+-------------+-------+https://stackoverflow.com/questions/46447587
复制相似问题