【问题标题】:How can I search by two continuous rows in SQL?如何在 SQL 中搜索两个连续的行?
【发布时间】:2015-10-09 01:41:58
【问题描述】:

给定 SQL 表

id     date       employee_type  employee_level
1   10/01/2015        other            2
1   09/13/2011      full-time          1
1   09/25/2010       intern            1
2   09/25/2013      full-time          3
2   09/25/2011      full-time          2
2   09/25/2008      full-time          1
3   09/23/2015      full-time          5
3   09/23/2013      full-time          4

是否可以搜索具有employee_type "intern" 的一行的id,以及在表中它上面的行(具有较晚日期的相同id)具有employee_type "full-time" 的行。

在这种情况下,id 1 符合我的要求。

非常感谢!

【问题讨论】:

  • 当你说“上一个”时,你是如何排序的?通过date 列?
  • SQL 表中没有隐含的行顺序。 “以前”是什么意思?你的意思是同一个 id 有更早的日期吗?
  • 我不认为要求是基于行的顺序,而是基于对实习生和全职 id 的需求
  • 为什么是 3 条记录? ,根据你的描述..它假设只返回两行,employee_level = 2不会被包含,因为类型是other,或者你的意思是当你遇到那个序列时,你会返回所有的id?
  • @bitfiddler 谢谢。以前我的意思是以后日期相同的ID。表中的上一行。

标签: sql database peoplesoft


【解决方案1】:

假设你的意思是和前一个日期相同的id,那么你可以使用lag(),大多数数据库都支持的ANSI标准函数:

select t.*
from table t
where t.id in (select id
               from (select t.*,
                            lag(employee_type) over (partition by id order by date) as prev_et
                     from table t
                    ) tt
               where tt.employee_type = 'intern' and tt.prev_et = 'full-time'
              );

如果您的数据库不支持lag(),您可以对相关子查询执行类似操作。

【讨论】:

  • 谢谢!我刚刚更新了问题以使其更清楚。我认为使用 lag() 是解决它的正确方法。
【解决方案2】:

我认为请求与问题中描述的不符;相反,您似乎想要的是列出实习生的所有行。

SELECT
      t1.*
FROM yourtable AS t1
      INNER JOIN (
            SELECT DISTINCT
                  id
            FROM yourtable
            WHERE employee_type = 'intern'
      ) AS t2 ON t1.id = t2.id
;

或者,您可能只想要那些既是“实习生”又是“全职”的人,在这种情况下,您可以使用下面使用 HAVING 子句的查询:

SELECT
      t1.*
FROM yourtable AS t1
      INNER JOIN (
            SELECT id
            FROM yourtable
            WHERE employee_type = 'intern'
                  OR employee_type = 'full-time'
            GROUP BY id
            HAVING COUNT(DISTINCT employee_type) > 1
      ) AS t2 ON t1.id = t2.id
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2011-02-22
    • 2023-02-04
    相关资源
    最近更新 更多