我有三张桌子
1。卡
CardNo CreateDate 12345678 01-01-15 34567876 01-05-15 45634455 01-05-16 12347689 01-02-15 43215678 01-05-15 87654445 01-05-15
和 2。 Account2Card
AccountNo CardNo 123456 12345678 123456 34567876 123456 45634455 654321 12347689 654321 43215678 654321 87654445
一个accountno有多个cardno,我想获得最后创建的cardNo如下
需要输出
AccountNo CardNo CreateDate 123456 45634455 01-05-16 654321 87654445 01-05-15
并将此结果集连接到另一个表 3。交易
Id accountno value 1 123456 5000 2 654321 6000
最终输出如下
AccountNo CardNo CreateDate value 123456 45634455 01-05-16 5000 654321 87654445 01-05-15 6000
我该如何解决?
答案 0 :(得分:1)
进行三向联接并使用行号选择与每个帐户的最大卡号对应的记录。
SELECT
AccountNo, CardNo, CreateDate, value
FROM
(
SELECT t1.AccountNo, t2.CardNo, t2.CreateDate, t3.value,
ROW_NUMBER() OVER (PARTITION BY t1.AccountNo ORDER BY t2.CardNo DESC) rn
FROM Account2Card t1
LEFT JOIN Card t2
ON t1.CardNo = t2.CardNo
LEFT JOIN Transaction t3
ON t2.AccountNo = t3.accountno
) t
WHERE
t.rn = 1;