MySQL SUM()基于多个条件

时间:2017-03-16 12:08:17

标签: mysql sql sum

我需要帮助重写查询。我目前只有一张桌子'排行榜'有4个字段

+-----------+------------+----------+-----------------+
| profileid | scoretotal | matchwon | datematchplayed |
+-----------+------------+----------+-----------------+

我试图创造一个“梯子”#39;这个视图向我展示了一个独特的profileids列表,其中包含了' ladderscore'是过去21天内profileids最佳20场比赛的总得分。

我在下面的陈述给了我正确的输出,但有没有办法重写这个,所以它不使用drop / create temptable?

DROP TABLE IF EXISTS templeaderboard;
CREATE TABLE templeaderboard (INDEX(id), INDEX(profileid)) AS
( SELECT * FROM realleaderboard WHERE datematchplayed > unix_timestamp() - 1814400 ) ;

SELECT a.profileid, SUM(IF(a.matchwon = 1, a.scoretotal * 1.5, a.scoretotal)) AS ladderscore
FROM templeaderboard AS a
WHERE (SELECT COUNT(*) FROM templeaderboard AS b
       WHERE b.profileid = a.profileid AND b.scoretotal >= a.scoretotal) <= 20
GROUP BY a.profileid
ORDER BY ladderscore DESC;

1 个答案:

答案 0 :(得分:0)

在我看来,你所有的临时表都在减少实际表的总行数。

如果这是正确的,您应该将临时表中的where子句移动到最终查询,并将最终查询的where条件更改为having。< / p>

SELECT  a.profileid,
        SUM(IF(a.matchwon = 1, a.scoretotal * 1.5, a.scoretotal)) AS ladderscore
FROM   realleaderboard AS a
JOIN   realleaderboard AS b
ON     a.profileid = b.profileid and b.scoretotal >= a.scoretotal
WHERE  a.datematchplayed > unix_timestamp() - 1814400 AND
       b.datematchplayed > unix_timestamp() - 1814400
GROUP BY a.profileid
HAVING count(*) <= 20
ORDER BY ladderscore DESC;

这可能需要一些调整,但它应该给你一般的想法。