SQL SERVER 求中位数和众数
1、背景
偶然发现一道很有意思的sql题:
一未排序奇数单链表list(num,position),其中num为不同的数字,position为num在链表中的位置,要求给出链表的中位数和众数。
2、思路
·中位数,比它大的、比它小的各占链表一半,即比它大的和比它小的数目相等。
·众数较为简单,选出出现次数最多的num即可。
一开始写题的时候没有头绪,因此选择了我个人较常用的方法(虽然平时不太推荐),即多建立临时表,将所需参数给出即可。
3、代码展示
本处主要介绍实现解题的代码!
- 中位数
select num
from (select num,count(*) as a
from list l1
where num in (select num
from list l2
where l1.num>l2.num;)
group by num;) table1
(select num,count(*) as b
from list l3
where num in (select num
from list l4
where l3.num>l4.num;)
group by num;) table2
where table1.num = table2.num
and table1.a = table2.b;
在本题中,由于知道了比中位数大的和比中位数小的的num数应该相同,故写出了两个找出比自身大(小)的数的个数的表,并进行连接判断。
2.众数
众数相比中位数更简单,话不多说,直接上代码!
/*
第一种方法,求出众数并给出有多少
*/
select num,max(c)
from (select num,count(*) as c
from list
group by num;) table3
group by num;
/*
第二种方法
*/
select num
from (select num,count(*) as p
from list
group by num;) table4
where p>= all(select count(*)
from list
group by num;);
4、总结
第一次做使用sql选择中位数和众数的题,感觉很新鲜,初看有种算法的味道,刚好最近也在刷算法题,写下自己第一篇,记录一下吧。
本文档到此结束