在Table中,我需要查出那个ID出现的频率最小,
select count(c1) from table where id=1,
select count(c1) from table where id=2
select count(c1) from table where id=3
select count(c1) from table where id=4,
最后查出来的结果理想是
0
1
2
3
不知道有没有好一点的思路,不想在代码里做个傻循环,需要注意的是ID可能为空
即select * from table where id=1有可能无结果集
select count(c1) as xx from table group by id order by xx
忘记补充一句,ID数目是在一定范围的
楼上,注意我想要的结果了么,
select count(c1) as num from table group by id having id in (1,2,3,4) order by num
@3楼,不知道你有亲自试过么,如果1在table中不存在呢,再说我想要的是出现次数最少的ID,可能描述有部分错误
http://bbs.csdn.net/topics/330092271
产生了数字,然后outer join
select id from(select id,count(c1) as num from table where id in(1,2,3,4) group by id)group by id having num=min(num)
还是count,group by,having那几个东西,自己多试几次就出来了
这种查询的话你可以用类似桶排序的办法,你要取Id为1 2 3 4 的出现次数的话,
创建一个长度为4的数组 初始值都为0,a[0]到a[3]分别代表id1234出现的次数。
遍历表,出现id=1的话a[0]+=1…其余的也一样,最后输出数组元素就是相应ID出现的次数了
select id,count(c1) from table group by id
你的意思是id范围是固定的集合,比如1、2、3、4、5,在table里可能某个id是不存在的,那么这个id出现的次数就是0,也就是最小的;
如果都出现,那么就是取最小的那个,是这样的意思吧?
假设你的id范围是0,1,2,3,4,5,表里的次数分别是
id,cs
0,8
1,9
3,7
5,8
其中2,4是0次。
select id from (
with t_id as
(select substr(t.ca,instr(t.ca,',',1,c.lv)+1,instr(t.ca,',',1,c.lv+1)-(instr(t.ca,',',1,c.lv)+1)) as id
from (select ',0,1,2,3,4,5,' as ca,length(',0,1,2,3,4,5,')-nvl(length(replace(',0,1,2,3,4,5,',',')),0)-1 as cnt from dual) t,
(select level lv from dual connect by level<=10) c
where c.lv<=t.cnt)
,t_cs as
(select id,sum(cs) cs from tmp_t group by id)
select t_id.id,rank() over (order by nvl(t_cs.cs,0)) rk from t_id,t_cs where t_id.id=t_cs.id(+))
where rk=1
结果是2,4
解释一下:
t_id,是把你的id范围0,1,2,3,4,5,转换成一个6行的临时表;如果你的id范围是从其他表里来的,那么直接select distinct id from id范围表 就可以了
t_cs,是table表里根据id分组统计的出现次数
外链接t_id.id=t_cs.id(+),把数值范围取全,配合nvl(t_cs.cs,0),如果没有出现,次数就=0
rank是排名,次数出现小的排第一,这里有2个数字次数都是0,并列第一,rank都是1,所以都取出来了,如果只要任取一个,把rank改为row_number就可以了
select id, count(id) as c from table where id is not null group by id order by c
要取最小的可以加上 top 1
要范围就改一下那个where
select id, count(id) as c from table where id is not null and id >= 0 and id <= 4 group by id order by c
select count(c1) as xx from table where id in(1,2,3,4) group by id order by xx having count(c1)>0
1.在表中查询符合条件的ID的出现次数,并存储在临时表#TEMP中( ID Between 1 and 5 意思为 取出 1 到 5 的ID)
select id,COUNT(c1) as NUM into #TEMP from TABLE where ID Between 1 and 5 GROUP BY id
2.查询临时表#TEMP中出现次数最小的值(大于0),
select * FROM #TEMP WHERE NUM in (select MIN(NUM) FROM #TEMP Where NUM > 0 )
3.删除临时表
drop table #TEMP