jingzh

1 mysql

1.1 方法一

select a.* 
from
(
select t1.*,(select count(*)+1 from 表 where 分组字段=t1.分组字段 and 排序字段<t1.排序字段) as group_id
from 表 t1
) a
where a.group_id<=3

1.1.1 方法分析

在查询列中使用嵌套子查询,在嵌套子查询中用要分组的字段作为关联字段,采用内关联,分组字段不是唯一的,查出就会翻倍,再用排序字段错位比较大小,就可以得出条数。但是 把条数查询不是放在列中而是放在where后就只会有一个条数,而不会每行都有条数,如下:(假定只查询部门编号是20)

把求行数子查询放在where后面
select * from employee e1 ,employee e2 where e1.deptno=e2.deptno 
 and e1.sal<e2.sal and e1.deptno = \'20\'

在这里插入图片描述
再对其求行数处理:(假定只查询部门编号是20)

把求行数子查询放在where后面
select count(*) from employee e1 ,employee e2 where e1.deptno=e2.deptno 
 and e1.sal<e2.sal and e1.deptno = \'20\'

在这里插入图片描述
要想能查出前三行,并且每行都显示行数,就必须这样处理:(假定只查询部门编号是20)

select t1.*,(select count(*)+1 from employee where deptno=t1.deptno and sal<t1.sal) as group_id
from employee t1 where t1.deptno = \'20\'

缺点:如果一个部门下存在同样的工资金额,那么就会有两个一样的行号了

1.2 方法二

SELECT
    *
FROM
    employee tpn
WHERE
    3 > (
        SELECT
            COUNT(*)
        FROM
            employee t
        WHERE
            tpn.deptno = t.deptno AND tpn.sal <= t.sal
    )

1.3 方法三

方法三可以解决同部门下相同工资却有同样排序编号问题

SET @rank:=0;
SELECT * FROM 
(SELECT a.*,
	IF(@tmp=deptno,@rank:=@rank + 1,@rank:=1) AS group_id,
	@tmp:=deptno AS tmp
	
	FROM employee a  ORDER BY deptno,sal DESC) b
WHERE b.group_id<=5

如图:
在这里插入图片描述

1.3.1 SQL分析

采用了局部变量方法,mysql变量详情理解:https://jingzh.blog.csdn.net/article/details/96328410
倘若只有一条信息,可能会让临时变量一直增加所以先这样设置SET @rank:=0;
核心语句:
IF(@tmp=deptno,@rank:=@rank + 1,@rank:=1)则利用中间变量@tmp存储上一条记录的deptno,并和当前的对比,如若相同,则序号@rank增加1,否则初始化@rank为1
@tmp:=deptno AS tmp则用于将当前的province_name值记录下来,供下一条记录使用

2 oracle

SELECT t.*         
   FROM (SELECT ROW_NUMBER() OVER(PARTITION BY 分组字段 ORDER BY 排序字段 DESC) rn,         
         b.*         
         FROM 表 b) t         
  WHERE t.rn <= 3  ;

此处使用了析构函数
Oracle中的分析函数over()的详细解析
两种写法都是获取分组中的伪列序号为目的

分类:

技术点:

相关文章:

  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
  • 2022-02-18
  • 2022-01-01
  • 2022-01-01
  • 2021-07-08
  • 2021-10-31
猜你喜欢
  • 2022-01-01
  • 2021-11-18
  • 2021-11-18
  • 2021-12-18
  • 2021-12-11
相关资源
相似解决方案