您好我有银行客户的交易表。表的名称是CUST_TRANSACTION。它有一些字段,如CUST_ID,TRANSACTION_DATE等。我想编写一个查询,以便我可以选择3个特定客户ID的最后一个事务。例如,
TRANSACTION_ID | CUST_ID | TRANSACTION_DATE | TRANSACTION_DESC
100023 | 2 | 15-12-2014 06:00 | Withdraw 1000 dollars
100022 | 5 | 14-12-2014 16:00 | Deposit 1000 dollars
100021 | 5 | 14-12-2014 15:00 | Withdraw 500 dollars
100020 | 4 | 12-12-2014 15:00 | Withdraw 300 dollars
100019 | 4 | 12-12-2014 14:39 | Deposit 300 dollars
100018 | 2 | 12-12-2014 15:00 | Withdraw 60 dollars
我想获得ids 2,4,5的最后一笔交易
TRANSACTION_ID | CUST_ID | TRANSACTION_DATE | TRANSACTION_DESC
100023 | 2 | 15-12-2014 06:00 | Withdraw 1000 dollars
100022 | 5 | 14-12-2014 16:00 | Deposit 1000 dollars
100020 | 4 | 12-12-2014 15:00 | Withdraw 300 dollars
我应该如何处理它?</ p>
编辑:到目前为止,我已尝试过这个
select *
from CUST_TRANSACTION
where CUST_ID IN('2', '5', '4')
and rownum <4
order by transaction_date desc
答案 0 :(得分:1)
你应该试试这个
SELECT CUST_ID , a.TRANSACTION_ID, TRANSACTION_DATE , TRANSACTION_DESC from CUST_TRANSACTION AS a
INNER JOIN (SELECT MAX(TRANSACTION_ID) TRANSACTION_ID FROM CUST_TRANSACTION GROUP BY CUST_ID) AS b ON a.TRANSACTION_ID=b.TRANSACTION_ID
答案 1 :(得分:1)
使用rank()获取顶部项目,然后仅为每个项目选择排名靠前的行。例如:
SELECT *
FROM (
select
transaction_id,
cust_id,
transaction_date,
transaction_desc,
rank() OVER (PARTITION BY cust_id ORDER BY cust_id, transaction_date desc) AS rank_id
from cust_transaction
) ct
WHERE ct.rank_id = 1
请参阅SQL Fiddle。
答案 2 :(得分:0)
试试这个
select t1.TRANSACTION_ID ,
t1.CUST_ID ,t1.TRANSACTION_DATE ,t1.TRANSACTION_DESC from table t1
inner join
(
select CUST_ID ,min(TRANSACTION_DATE) as TRANSACTION_DATE from table
group by CUST_ID
) t2
on t1.CUST_ID=t2.CUST_ID and t1.TRANSACTION_DATE =t2.TRANSACTION_DATE
答案 3 :(得分:0)
按客户ID分组并获取最大值(transaction_date)。获取具有此客户ID和transaction_date组合的记录