Mysql 行中的分组范围

Grouping Ranges In Rows In Mysql

我有很多行,我想知道存在的各种数据范围。

使用此代码

select
     count(CASE WHEN the_amount BETWEEN 2000 AND 3000 THEN 1 END) as '2000 to 3000',
     count(CASE WHEN the_amount BETWEEN 3001 AND 4000 THEN 1 END) as '3001 to 4000',
     count(CASE WHEN the_amount BETWEEN 4001 AND 5000 THEN 1 END) as '4001 to 5000',
     count(CASE WHEN the_amount BETWEEN 5001 AND 6000 THEN 1 END) as '5001 to 6000'
 from r_data where transaction_type = 'send'

我可以计算范围,但这只会产生一行。

我想要的是这种格式的数据

+------+------+----------+
| From | To   | count(*) |
+------+------+----------+
|  2000 |    3000 |    3 |
|  3001 |    4000 |    4 |
|  4001 |    5000 |    2 |
|  5001 |    6000 |    1 |
+------+------+----------+

我正在尝试编写这样的代码

SELECT
    2000 as 'from',
    3000 as 'to',
    COUNT(*) as 'occurence'
FROM r_data where transaction_type = 'send'
GROUP BY the_amount;

但这只显示 20003000,并没有给出正确的结果 count.How 我可以编写一个查询来生成我想要的格式吗?

试试这个:

SELECT
  vals.val AS `From`,
  vals.val+999 AS `To`,
  COUNT(*) AS `Count`
FROM
  r_data
  INNER JOIN (
     SELECT 1 AS val
     , UNION SELECT 1001
     , UNION SELECT 2001
     , UNION SELECT 3001
     , UNION SELECT 4001
     , UNION SELECT 5001
     , UNION SELECT 6001
     -- , ....
  ) AS vals 
    ON r_data.the_amount>=vals.val 
    AND r_data.the_amount<(vals.val+1000) 
GROUP BY vals.val

如果您不知道您的总 val 个范围,但您知道您需要 1000 个大小的桶,您可以这样做:

SELECT COUNT(*) `count`,
       1000*FLOOR(val/1000) `from`,
       1000*FLOOR(val/1000)+999 `to`
  FROM r_data
 WHERE transaction_type = 'send'
 GROUP BY FLOOR(val/1000)

表达式 GROUP BY FLOOR(val/1000) 可以将您的值聚合成 1000 个块。

您还可以将 ORDER BY COUNT(*) DESC 添加到此查询以找到最大的值块,并进行其他此类数据显示操作