当前位置:   article > 正文

每日刷一刷力扣SQL(八)_力扣sql刷题路线

力扣sql刷题路线

185.部门工资前三高的所有员工

考察点:窗口函数的使用

  1. select
  2. d.name as Department ,
  3. t.name as Employee,
  4. t.salary as Salary
  5. from (
  6. select
  7. * ,
  8. DENSE_Rank() over(PARTITION BY departmentId order by salary DESC) as rank_id
  9. from Employee
  10. ) t join Department d on t.departmentId = d.id
  11. where rank_id <=3

其他解法: 

  1. SELECT
  2. Department.NAME AS Department,
  3. e1.NAME AS Employee,
  4. e1.Salary AS Salary
  5. FROM
  6. Employee AS e1,Department
  7. WHERE
  8. e1.DepartmentId = Department.Id
  9. AND 3 > (SELECT count( DISTINCT e2.Salary )
  10. FROM Employee AS e2
  11. WHERE e1.Salary < e2.Salary AND e1.DepartmentId = e2.DepartmentId )
  12. ORDER BY Department.NAME,Salary DESC;

1667.修复表中的文字

 考察点:字符串处理函数 concat(),upper(),lower(),substring()

  1. select
  2. user_id,
  3. concat(upper(LEft(name,1)),lower(substring(name,2))) as name
  4. from Users
  5. order by user_id ASC
  1. select user_id,concat(upper(left(name, 1)), lower(right(name, length(name) - 1))) as name
  2. from users
  3. order by user_id

1527.患某种疾病的患者

使用SQL匹配正则表达式

常见正则表达式模式

  • ^:匹配字符串的开头。
  • $:匹配字符串的结尾。
  • .:匹配任意单个字符。
  • [abc]:匹配方括号内的任意一个字符。
  • [a-z]:匹配指定范围内的字符。
  • *:匹配前面的字符零次或多次。
  • +:匹配前面的字符一次或多次。
  • ?:匹配前面的字符零次或一次。
  • {n}:匹配前面的字符恰好 n 次。
  • |:表示逻辑或,匹配 | 两侧的任意一个表达式。
  1. select *
  2. from Patients
  3. where conditions REGEXP '^DIAB1|\\sDIAB1'

196.删除重复的电子邮箱

慢查询优化经验的同学会清楚,在实际生产中,面对千万上亿级别的数据,连接的效率往往最高,因为用到索引的概率较高。

  1. delete p1 from Person p1 , Person p2
  2. where
  3. p1.Email = p2.Email and p1.ID > p2.ID

a. 从表p1取出3条记录;
b. 拿着第1条记录去表p2查找满足WHERE的记录,代入该条件p1.Email = p2.Email AND p1.Id > p2.Id后,发现没有满足的,所以不用删掉记录1;
c. 记录2同理;
d. 拿着第3条记录去表p2查找满足WHERE的记录,发现有一条记录满足,所以要从p1删掉记录3;
e. 3条记录遍历完,删掉了1条记录,这个DELETE也就结束了。

176.第二高的薪水

思路:使用limit 和 offset

limit n子句表示查询结果返回前n条数据

offset n表示跳过x条语句

limit y offset x 分句表示查询结果跳过 x 条数据,读取前 y 条数据

使用limit和offset,降序排列再返回第二条记录可以得到第二大的值。

  1. select
  2. ifNULL((
  3. select
  4. distinct salary from Employee
  5. order by salary DESC
  6. limit 1,1
  7. ),null)
  8. as SecondHighestSalary

另一种思路:比薪水最大的还要小的一条数据

  1. select ifNULL(max(salary),NULL) as SecondHighestSalary
  2. from Employee
  3. where salary < (
  4. select max(distinct salary) from Employee
  5. )

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/1021280
推荐阅读
相关标签
  

闽ICP备14008679号