MYSQL - 过去10天的SUM值

时间:2017-07-02 21:04:00

标签: mysql date if-statement sum case

我在mysql中有这个表:

|   player1   |  player2 |    date    |   fs_1   |   fs_2   |
    Jack         Tom       2015-03-02       10         2
    Mark        Riddley    2015-05-02       3          1 
     ...

我需要知道玩家1在date_g中报告的比赛之前已经完成了多少次(fs_1)(比如前10天)。

这是我尝试没有成功的原因:

选项1

    SELECT 
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(IF(date_sub(date_g, interval 10 day)< date_g, FS_1, 0)) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;

选项2

SELECT 
    players_atp.name_p AS 'PLAYER 1',
    P.name_p AS 'PLAYER 2',
    DATE(date_g) AS 'DATE',
    result_g AS 'RESULT',
    FS_1,
    FS_2,
    SUM(CASE WHEN date_g between date_g and date_sub(date_g, interval 10 day) then fs_1 else 0 end) AS 'last 10 days'
FROM
    stat_atp stat_atp
        JOIN
    backup3.players_atp ON ID1 = id_P
        JOIN
    backup3.players_atp P ON P.id_p = id2
        JOIN
    backup3.games_atp ON id1_g = id1 AND id2_g = id2
        AND id_t_g = id_t
        AND id_r_g = id_r
WHERE
    date_g > '2015-01-01'
GROUP BY ID1;

我编辑了代码,现在更容易阅读和理解。

 SELECT 
     id1 AS 'PLAYER 1',
     id2 AS 'PLAYER 2',
     DATE(date_g) AS 'DATE',
     result_g AS 'RESULT',
     FS_1,
     FS_2,
     SUM(CASE
         WHEN date_g BETWEEN date_g AND DATE_SUB(date_g, INTERVAL 10 DAY) THEN fs_1
     END) AS 'last 20 days' FROM
     stat_atp stat_atp
         JOIN
     backup3.games_atp ON id1_g = id1 AND id2_g = id2
         AND id_t_g = id_t
         AND id_r_g = id_r GROUP BY ID1;

提前完成。

1 个答案:

答案 0 :(得分:0)

也许这可以帮到你:

SELECT 
    id1,
    SUM(fs_1)
FROM 
     stat_atp
WHERE
     date_g <= DATE_SUB('2015-03-02', INTERVAL 1 DAY) AND date_g >= DATE_SUB('2015-03-02', INTERVAL 10 DAY)
AND
    id1='Jack'
GROUP BY id1;

请记住,RDBMS用于构建严格的数据集,这些数据集通过明确的ID(在讨论SQL时 keys )之间相互链接。尊重三种正常形式更容易。这就是为什么你应该使用键来识别你的匹配本身。通过这种方式,您可以使用子查询(子集)来实现目标。

然后,请记住SQL STRUCTURED 。这是它的力量和弱点,因为你无法将它用作具有循环和条件的图灵完整编程语言。但在任何情况下,您都可以为查询找到相同的结构。但是,您可以使用另一个语言与SQL查询结果进行交互,并在结果集本身上使用循环和条件。随你(由你决定。

无论如何,您可能想要阅读与ISO SQL表单不同的MySQL GROUP BY子句:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html