在Mysql中的行中分组范围

时间:2015-01-24 13:51:01

标签: mysql aggregate-functions histogram

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

使用此代码

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'

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

enter image description here

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

+------+------+----------+
| 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并且没有事件给出正确的计数。如何编写查询以生成我想要的格式?。

2 个答案:

答案 0 :(得分:1)

如果你不知道你的总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以查找最大的值块,并执行其他此类数据显示操作

答案 1 :(得分:0)

试试这个:

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