如何获取每个玩家的最后一笔交易 - SQL 解决方案

How to get the last transaction of each player - SQL Solution

我有一个数据库,用于存储游戏中进行的所有交易 (picture of DB)。现在我想获取每个玩家的最后一笔交易的价值。

我已经试过了:

SELECT MAX(timestamp), value, account_id
FROM transactions
GROUP BY account_id;

在这里我得到了正确的时间和 account_id,但不是正确的值。

只用SQL就可以解决这个问题吗?

select * from table 
where id in (select MAX(id) from table group by account_id)

在 MySQL 8 或更高版本中,您可以为此使用 window 函数:

with cte as (
    select *, row_number() over (partition by account_id order by timestamp desc) as rn
    from transactions
)
select *
from cte
where rn = 1