我有两张桌子..
1-Identity(id, ref1,ref2, address)
2-details(ref1,ref2,amount,u_no,u_date)
我想用具有最高u_date和最高u_no
的金额之和来提取每个id我在下面尝试过 -
Select I.id, d.amount
From identity I Inner Join
(select ref1,ref2,sum(amount) as amount
From details d
where (ref1,ref2,u_no,u_date) In (select ref1, ref2, max(u_no) as u_no, max(u_date) as u_date from details group By ref1,ref2)
Group By ref1,ref2)
) d
On I.ref1 = d.ref1 And I.ref2 = d.ref2;
但是我得到了多个相同的id。 Table details and expected output
有人可以帮我解决这个问题。谢谢
答案 0 :(得分:0)
这是你想要的吗?
select d.*
from (select d.*,
row_number() over (partition by ref1, ref2 order by u_date desc, u_no desc) as seqnum
from details d
) d
where seqnum = 1;
答案 1 :(得分:0)
所需的结果可以简单地完成:
Select id,max(amount) AS amount
From identity
Join ref
using (Ref1,Ref2)
Group by id
如果你在结果中需要更多的列,但每个id只需要一个,请改变所需的输入输出以反映这一点,我们可以帮助解决这个问题,但很可能涉及到Gordon向你展示的row_number()技巧