mysql随笔

## 1、编写一个 SQL 查询,查找所有至少连续出现三次的数字。
在这里插入图片描述

答案1:

借此学习mysql定义变量的用法

SELECT
   distinct	num AS ConsecutiveNums 
FROM
	(
	SELECT
		r.num,
	IF
		( @num = r.num, @i := @i + 1, @i := 1 ) count,
		@num := r.num tt 
	FROM
		( SELECT * FROM `Logs` l,( SELECT @i := 0 ) t ) r 
	) z 
WHERE
	count > 2;

答案2:

二维数组也可以用in

SELECT DISTINCT
	Num AS ConsecutiveNums 
FROM
	`Logs` 
WHERE
    	( Id + 1, Num ) IN ( SELECT * FROM `Logs` ) 
	AND ( Id + 2, Num ) IN (SELECT* FROM`Logs`);

2、部门工资最高的员工

答案一:主要用到开窗函数
MySQL8.0以上版本才能使用窗口函数

SELECT
	d.NAME Department,
	k.NAME EMPLOYEE,
	k.salary Salary 
FROM
	(
	SELECT
		p.* 
	FROM
		EMPLOYEE p,(
		SELECT
			g.NAME,
			g.salary,
			g.departmentId,
			ROW_NUMBER() over ( PARTITION BY g.departmentId ORDER BY g.salary DESC ) rn 
		FROM
			EMPLOYEE g 
		) kk -- 这一层查询为了查出每个部门最高的工资
	WHERE
		kk.salary = p.salary 
		AND kk.departmentId = p.departmentId 
		AND kk.rn = 1 
	) k,   -- 重新关联员工表是因为最高工资可能不止一个人
	DEPARTMENT d 
WHERE
	k.departmentId = d.id;
          

答案2:

SELECT
	d.NAME Department,
	g.NAME EMPLOYEE,
	g.salary Salary 
FROM
	EMPLOYEE g,
	Department d 
WHERE
	( g.departmentId,g.salary) IN (SELECT departmentId, max(salary) FROM EMPLOYEE  GROUP BY departmentId) 
	  -- 二维数组也可以用in 和上面分组以后获取有异曲同工之妙
	AND g.departmentId = d.id;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值