同一交易的多个日期和状态

时间:2014-08-13 18:57:04

标签: mysql oracle multiple-columns

TRANS_ID    MEMBERSHIP_NO   BUSINESS_PROCESS_NO STATUS  END_DATE         ISSUE_DATE
------------------------------------------------------------------------------------
1234       45678             AB                   W     1/9/2013 11:57   2-Jan-13
1234       45678             AB                   F     1/9/2013 11:59   2-Jan-13
1234       45678             AB                   P     1/10/2013 13:14  2-Jan-13

我有一张类似于上面的表格。我有相同的trans_idmembership_no以及business_process_no,但状态和结束日期不同。

我希望能够根据trans_idmembership_no提取信息,因为这些是我的其他表的外键。但我只想要一行根据END_DATE列基于最早出现的信息提供给我的信息:

TRANS_ID    MEMBERSHIP_NO   BUSINESS_PROCESS_NO STATUS  END_DATE         ISSUE_DATE
------------------------------------------------------------------------------------
1234       45678             AB                   W     1/9/2013 11:57   2-Jan-13

谢谢

1 个答案:

答案 0 :(得分:0)

      SELECT DISTINCT t1.*
        FROM table_name t1
   LEFT JOIN table_name t2
          ON t2.trans_id = t1.trans_id
         AND t2.membership_no = t1.membership_no
         AND t2.end_date > t1.end_date
   LEFT JOIN table_name t3 /* Necessary when MIN(end_date) is duped */
          ON t3.trans_id = t1.trans_id
         AND t3.membership_no = t1.membership_no
         AND t3.end_date = t1.end_date
         AND t3.issue_date > t1.issue_date 
   LEFT JOIN table_name t4 /* Necessary when MIN(issue_date) is duped */
          ON t4.trans_id = t1.trans_id
         AND t4.membership_no = t1.membership_no
         AND t4.end_date = t1.end_date
         AND t4.issue_date = t1.issue_date 
         AND t4.status > t1.status  
       WHERE t1.trans_id = 1234
         AND t1.membership_no = 45678
         AND t2.trans_id IS NULL
         AND t3.trans_id IS NULL
         AND t4.trans_id IS NULL

这假设没有主键,我自己选择了重写顺序偏好。