dept表: emp表:
题目:计算dname = ‘Research Institude’的员工工资中位数
中位数是指:一组按照大小排列起来的数据中处在中间位置的数,当有奇数个(如17个)时,中间数就是中间那个数(第9个);当有偶数个(如18个)数据时,中间数就是中间那两个数的平均值(第9个和第10个的平均值)
set @rowindex:=0;
select AVG(sal)
from
(select @rowindex := @rowindex + 1 as myindex,sal
from emp
where deptno in
(select deptno
from dept
where dname = 'Research Institude')
ORDER BY sal)as e
where myindex in (FLOOR(@rowindex/2+1),CEIL(@rowindex/2))
过程分析:7-9行子查询表示找出dname为Research Institude的deptno。4-10行通过子查询过滤不在Research Institude里的员工,并查询其 序号、工资。最外层查询筛选出在(FLOOR(@rowindex/2+1),CEIL(@rowindex/2))集合中的序号,然后计算筛选出来的工资的平均值。
CEILING(X)
Returns the smallest integer value not less than X.
返回不小于X的最小整数值。(天花板)
FLOOR(X)
Returns the largest integer value not greater than X.
返回不大于X的最大整数值。(地板)
所以当@rowindex=5(有5行数据)时,floor(@rowindex/2+1)返回3,ceil(@rowindex/2)返回3,中位数为第3行数据;当@rowindex=6时,floor(@rowindex/2+1)返回4,ceil(@rowindex/2)返回3,中位数为第3行第4行数据平均值。