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

icnyk63a  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(463)

我很不好意思问这样一个琐碎的sql问题,但我似乎找不到也找不出答案。
我有一列ID,其中一些出现了不止一次。我想计算每个id出现的次数,并对它们进行相应的分组。
例如:
编号:112 113 114 115 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

谢谢你的帮助,

ars1skjm

ars1skjm1#

我想你基本上需要直方图:

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 价值观。我不确定这对你需要做的事情是否真的很重要。

ijnw1ujt

ijnw1ujt2#

根据你对任务的描述,这应该能帮你完成任务。

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

这将产生一个所有id的列表,以及与该id相关联的出现次数的降序。我走这条路是因为你提到了射程是任意的。

相关问题