在 sql oracle 10g 中将两行配对在一起

pair two rows together in sql oracle 10g

我有下面的 table 结构

当员工的协议类型是基本协议和附录(例如第 1、2 和 5、6 行)时,这两行需要一起考虑,状态将是活动的。下面应该是预期的结果

如何在 oracle 10g 中实现这一点。谢谢

这可以使用 CASE 语句和 LEAD 分析函数来实现,以查看下一个 ID 是否为 Appendix.

查询

--This is to set up the sample data
WITH
    emp_agreements (id, emp_id, agreement_type)
    AS
        (SELECT 1, 1023, 'Basic' FROM DUAL
         UNION ALL
         SELECT 2, 1023, 'Appendix' FROM DUAL
         UNION ALL
         SELECT 3, 1023, 'Basic' FROM DUAL
         UNION ALL
         SELECT 4, 1023, 'Basic' FROM DUAL
         UNION ALL
         SELECT 5, 1023, 'Basic' FROM DUAL
         UNION ALL
         SELECT 6, 1023, 'Appendix' FROM DUAL)
--Real query begins here. You will need to put in your real table name
  SELECT emp_id, status
    FROM (SELECT id,
                 emp_id,
                 agreement_type,
                 CASE LEAD (agreement_type) OVER (PARTITION BY emp_id ORDER BY id)
                     WHEN 'Appendix' THEN 'Active'
                     ELSE 'Pending'
                 END    AS status
            FROM emp_agreements)
   WHERE agreement_type = 'Basic'
ORDER BY id;

结果

   EMP_ID     STATUS
_________ __________
     1023 Active
     1023 Pending
     1023 Pending
     1023 Active