SQL:计算两个值之间的出现次数

时间:2018-08-01 21:55:38

标签: mysql sql

我很尴尬地问这样一个琐碎的SQL问题,但我似乎找不到或没有找到答案。

我有一列ID,其中一些ID出现多次。我想计算每个ID的出现次数,并进行相应的分组。

例如:

  

ID:112 113 114 115 112 112 112

任意分组:1、2-5,> 5

最后得到回报

NUMBER OCCURRENCES 
1      3 
2-5    1
6+     0

代码?

SELECT "1" as NUMBER, 
COUNT(ID) AS OCCURRENCES 
FROM TABLE WHERE OCCURRENCES = 1
UNION
SELECT "2-5" as NUMBER,
COUNT(ID) AS OCCURRENCES
FROM TABLE WHERE OCCURRENCES BETWEEN 2 AND 5
UNION
SELECT "6+" as NUMBER,
COUNT(ID) AS OCCURRENCES
FROM TABLE WHERE OCCURRENCES > 5

谢谢您的帮助,

2 个答案:

答案 0 :(得分:2)

我认为您基本上想要一个直方图:

select cnt, count(*), min(id), max(id)
from (select id, count(*) as cnt
      from t
      group by id
     ) t
group by cnt;

您可以为此添加范围:

select (case when cnt = 1 then '1'
             when cnt <= 5 then '2-5'
             else '6+'
        end) as cnt_range, count(*), min(id), max(id)
from (select id, count(*) as cnt
      from t
      group by id
     ) t
group by cnt_range
order by min(cnt);

这不会产生0值。我不确定这对您需要做的事情真的很重要。

答案 1 :(得分:0)

仅根据您对任务的描述,这应该会让您前进。

SELECT [ID], COUNT([ID]) AS OCCURRENCES FROM t GROUP BY [ID], ORDER BY OCCURRENCES DESC

这将产生所有ID的列表以及与ID关联的出现次数降序排列。我走这条路是因为您提到范围是任意的。