MySQL使用max(date)和sum获取val

时间:2018-08-18 16:42:39

标签: mysql

这是我的问题。我有一个包含以下列的表格:

player_id | win_amount | loss_amount | datetime

每条记录均包含玩家的ID,获胜或失败的金额(其他字段为0)和日期时间。 我希望MySQL查询获得以下信息:

  • player_id
  • 该玩家的sum(win_amount) - sum(loss_amount)
  • 上一个非零loss_amount的日期时间
  • 上一个日期时间的loss_amount

1 个答案:

答案 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