加入Oracle的最高成绩

时间:2015-03-27 12:05:55

标签: oracle

我正在使用此查询:

SELECT * 
FROM HISTORY
LEFT JOIN CUSTOMER ON CUSTOMER.CUST_NUMBER = HISTORY.CUST_NUMBER
LEFT JOIN ( 
    Select LOAN_DATE, CUST_NUMBER, ACCOUNT_NUMBER, STOCK_NUMBER, LOC_SALE
    From LOAN
    WHERE ACCOUNT_NUMBER != 'DD'
    ORDER BY LOAN_DATE DESC
    ) LOAN ON LOAN.CUST_NUMBER  = HISTORY.CUST_NUMBER
order by DATE desc

但我只希望加入贷款表的最高结果(最近由Loan_date加入)。由于某种原因,它获得了三条记录(我看到的每一笔贷款都在客户身上)。我确定我错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:2)

如果您在每个cust_number加入最新的贷款行后,那么应该这样做:

select * 
from   history
       left join customer on customer.cust_number = history.cust_number
       left join (select loan_date,
                         cust_number,
                         account_number,
                         stock_number,
                         loc_sale
                  from   (select loan_date,
                                 cust_number,
                                 account_number,
                                 stock_number,
                                 loc_sale,
                                 row_number() over (partition by cust_number
                                                    order by loan_date desc) rn
                          from   loan
                          where account_number != 'DD')
                  where   rn = 1) loan on loan.cust_number  = history.cust_number
order by date desc;

如果每个cust_number有两行具有相同的loan_date,并且您想要检索两者,则更改row_number()的{​​{1}}分析函数。

如果您只想检索一行,那么您必须确保在订单中添加其他列,以确保绑定的行始终以相同的顺序显示,否则您可能会发现有时你会在后续的查询运行中返回不同的行。