记录一下 SQL 题|小册免费学

183 阅读1分钟

作为本小册的一个练习,找了一些个通用的sql解法

第N高

这种就是排序,然后分页取就行。

select distinct salary
      from Employee
      order by salary desc
      limit (N-1),1

或者是可以子查询,一个数据,只要找出 >= 的个数,这个个数=N就行:

select distinct t1.Salary
    from Employee t1
    where N = (
        select count(distinct t2.Salary)
        from Employee t2
        where t2.Salary >= t1.Salary
    )

里面的子查询就是找到比当前数据大的数,然后这个 count() = N 就行

树形结构中有N个子级的数目

表自连接,关联父级和子级的字段,然后分组,此时得到的就是子级,然后过滤就行:

select E1.Name
from Employee as E1 join Employee as E2 on(E1.id = E2.managerid)
group by E1.id,E1.Name
having count(E1.id) >= 5
select E1.Name,E2.Name
from Employee as E1 join Employee as E2 on(E1.id = E2.managerid)

上面查询到就是所以匹配的上下级关系,然后对 E1 这个父级进行分组,就是以这个父级为单位的全部结构。

连续出现的数字

看需要几次吧,如果是3次:

SELECT distinct L1.num AS ConsecutiveNums
FROM `Logs` AS L1
JOIN `Logs` AS L2 ON (L1.num = L2.num AND L1.id + 1 = L2.id)
JOIN `Logs` AS L3 ON (L2.num = L3.num AND L2.id + 1 = L3.id)

第一行,然后接到第二行,看第二行的id是否 = 第一行id+1

某个分组下的最高

举一个 leetcode 中的例子,一般这种会在多个表中取数据的,所以不可能太简单就取出来:

部门工资最高的员工

有员工表,部门表

  1. 先找到每一个部门的最高薪水
select D.id, D.name, max(E1.salary) as m
    from Department as D
    join Employee as E1 
        on (D.id = E1.departmentid)
    group by D.id,D.name
  1. 连接员工表
select F.name as `Department`,E.name as `Employee`,E.Salary
from Employee as E
join (
    select D.id,D.name,max(E1.salary) as m
    from Department as D
    join Employee as E1 
        on (D.id = E1.departmentid)
    group by D.id,D.name
) as F
    on (E.departmentid = F.id and E.salary = F.m);