答案 0 :(得分:0)
你可以这样做:
select *, sum(select sum(t1.poin)
from table t1
where t1.member_id = t.member_id
) as poin,
sum(select sum(t1.freq)
from table t1
where t1.member_id = t.member_id
) as freq
from table t
where trans_id = (select t1.trans_id
from table t1
where t1.member_id = t.member_id
order by t1.trans_id desc
fetch first 1 rows only
);
大多数 DBMS 都支持fetch first 1 rows only
方法。
如果您正在使用SQL Server,那么您可以直接将其表达为:
select t.member_id, tt.*
from (select *, row_number() over (partition by member_id order by trans_id desc) as seq
from table
) t cross apply (
select sum(t1.poin) as poin, sum(t1.freq) as freq
from table t1
where t1.member_id = t.member_id
) tt
where t.seq = 1;