从获得的两个表积分和积分损失中获取用户的等级

时间:2016-07-25 05:50:28

标签: mysql

我有两个MySQL表,一个用于获得积分,一个用于积分损失。表结构是:

Points Earned:
id user_id points_earned date_time

Points Loss:
id user_id points_loss date_time

我希望目前以total_points为基础获得用户排名,这是来自获得点数的总和 - 来自积分损失的总和。

如何通过MySQL查询获得所有用户的排名。

2 个答案:

答案 0 :(得分:1)

使用join和group by

select a.user_id, sum(a.points_earned )- sum(b.points_loss  )
from `Points Earned` as a
left join `Points Loss` as b on a.user_id = b.user_id
group by a.user_id

答案 1 :(得分:1)

如果表中每个用户有多个points_earned / points_loss行,则可以使用此查询:http://sqlfiddle.com/#!9/81b33/1

SELECT
    user_id,
    SUM(points) AS points
FROM
    (
        SELECT
            a.user_id,
            points
        FROM
            (
                SELECT
                    user_id,
                    SUM(points_earned) AS points
                FROM
                    points_earned
                GROUP BY
                    user_id
            ) AS a
        UNION
            SELECT
                user_id,
                SUM(points_loss) * - 1 AS points
            FROM
                points_loss
            GROUP BY
                user_id
    ) AS points
GROUP BY
    user_id
ORDER BY
    points DESC,
    user_id ASC

如果您希望在结果中将实际排名设为数字,则可以使用此查询:http://sqlfiddle.com/#!9/81b33/3

SELECT
    user_id,
    points,
    @curRank := IF (
                @prevRank = points,
                @curRank,
                @incRank
     ) AS rank,
     @incRank := @incRank + 1,
     @prevRank := points
FROM
    (
        SELECT
            *
        FROM
            (
                SELECT
                    @curRank := 0,
                    @prevRank := NULL,
                    @incRank := 1
            ) AS count,
            (
                SELECT
                    a.user_id,
                    points
                FROM
                    (
                        SELECT
                            user_id,
                            SUM(points_earned) AS points
                        FROM
                            points_earned
                        GROUP BY
                            user_id
                    ) AS a
                UNION
                    SELECT
                        user_id,
                        SUM(points_loss) * - 1 AS points
                    FROM
                        points_loss
                    GROUP BY
                        user_id
            ) AS points
        GROUP BY
            user_id
        ORDER BY
            points DESC,
            user_id ASC
    ) AS ranking