【问题标题】:Return all records that has particular record following next to it返回其旁边具有特定记录的所有记录
【发布时间】:2020-10-05 19:14:22
【问题描述】:

我几乎没有按序列号排序的记录,我需要所有记录,以便一个记录后跟另一个满足给定条件的记录。

学生表 -> CREATE TABLE 学生(sno int, id int, firstname varchar(255));

条件:记录应该有 firstname = "alex",并且后面必须有 firstname = "justin" 的记录

Input: 
    sno id firstname
    1   1   alex
    2   2   justin
    3   1   alex
    4   3   Seth
    5   2   justin
    6   1   alex
    7   2   justin
    8   2   justin

Output: 
    sno id firstname
    1   1   alex
    2   2   justin
    6   1   alex
    7   2   justin
    

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    你可以使用lead()/lag():

    select s.*
    from (select s.*,
                 lag(name) over (order by sno) as prev_name,
                 lead(name) over (order by sno) as next_name
          from student s
         ) s
    where (name = 'alex' and next_name = 'justin') or
          (name = 'justin' and prev_name = 'alex')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 2021-12-04
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多