最近的交易ID按贷款ID和日期

时间:2015-05-01 14:52:50

标签: date

我有3列,loan_code,tran_code和tran_date。对于每个loan_code,有几个tran_codes和几个tran_dates。对于每个loan_code,我需要获取最新的tran_code。

目前我的查询说:

    Select loan_code, max(tran_date) as tran_date, tran_code
    from loan_table
    group by loan_code, tran_code

这会导致loan_code重复使用不同的tran_codes。我只需要最近的一个。我也尝试在loan_code前面使用distinct,但这并没有改变任何东西。

    loan_code | tran_code | tran_date
    ---------------------------------
    2379778   | 37082762  | 2014-06-06
    2379778   | 39304394  | 2014-06-08
    4687613   | 35510651  | 2015-02-08
    4687613   | 37082762  | 2015-02-12

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT loan_code, tran_date, tran_code 
FROM loan_table table1
JOIN 
(SELECT loan_code,max(tran_date) as tran_date, tran_code
 FROM loan_table
 GROUP BY loan_code, tran_code
) table2
ON table1.loan_code= table2.loan_code
  AND table1.tran_date= table2.tran_date
  AND table1.tran_code= table2.tran_code