这是我的问题。我有一个包含以下列的表格:
player_id | win_amount | loss_amount | datetime
每条记录均包含玩家的ID,获胜或失败的金额(其他字段为0)和日期时间。 我希望MySQL查询获得以下信息:
player_id
sum(win_amount) - sum(loss_amount)
loss_amount
的日期时间loss_amount
答案 0 :(得分:0)
尝试使用GROUP BY
,一些聚合函数和Correlated Subqueries进行以下查询。将table
替换为您的实际表名:
SELECT
t1.player_id,
SUM(t1.win_amount) - SUM(t1.loss_amount) AS net_win_amount,
MAX(IF(t1.loss_amount > 0,
t1.datetime,
NULL)) AS last_loss_datetime,
(SELECT
t2.loss_amount
FROM
`table` AS t2
WHERE
t2.player_id = t1.player_id
AND t2.loss_amount > 0
ORDER BY t2.datetime DESC
LIMIT 0 , 1) AS last_loss_amount
FROM
`table` AS t1
GROUP BY t1.player_id