小编典典

SQL计算成功和失败的条纹

sql

如果我有一个如下所示的SQL表,该如何计算当前的赢或输连胜(以及按季节对赢/输连胜进行分组/重置)。我想更新表并为每条记录填写条纹。

因此,对于#1,条纹将为“ -1”,#2将为“ 1”,#3将为“ 2”,但是一旦我们降至#7,它将再次重置为“
1”。(+1表示“赢得1场比赛”,-1表示“失去1场比赛”,依此类推。)

ID    team    date         Result    season     streak
1     76ers   2000-01-01   Loss      2000       Null
2     76ers   2000-01-05   Win       2000       Null
3     76ers   2000-01-08   Win       2000       Null
4     Lakers  2000-01-03   Loss      2000       Null
5     Lakers  2000-01-07   Loss      2000       Null
6     Lakers  2000-01-01   Win       2000       Null

7     76ers   2002-03-01   Win       2001       Null
8     76ers   2002-03-05   Win       2001       Null
9     76ers   2002-03-08   Loss      2001       Null
10    Lakers  2002-03-03   Loss      2001       Null
11    Lakers  2002-03-07   Loss      2001       Null
12    Lakers  2002-03-01   Win       2001       Null

阅读 154

收藏
2021-04-28

共1个答案

小编典典

对于每个游戏,计算与之前结果相同的游戏,这样就不会有中间结果相反的游戏。将结果存储在临时表中:

CREATE TEMPORARY TABLE STREAK_TABLE
SELECT
    ID,
    (
        SELECT 1 + COUNT(*)                 -- Earlier games with the same result, team and season.
        FROM YOUR_TABLE T2
        WHERE
            T1.Result = T2.Result
            AND T1.team = T2.team
            AND T1.season = T2.season
            AND T1.date > T2.date
            AND NOT EXISTS (
                SELECT *                    -- The games in between, with the same team and season but opposite result.
                FROM YOUR_TABLE T3
                WHERE
                    T2.Result <> T3.Result
                    AND T1.team = T3.team
                    AND T1.season = T3.season
                    AND T3.date BETWEEN T2.date AND T1.date
            )
    ) S
FROM YOUR_TABLE T1

然后,更新原始表(并消除该过程中的丢失条纹):

UPDATE YOUR_TABLE
SET streak = (
    SELECT CASE Result WHEN 'Win' THEN S ELSE -S END
    FROM STREAK_TABLE
    WHERE STREAK_TABLE.ID = YOUR_TABLE.ID
)

最后,清理临时表:

DROP TABLE STREAK_TABLE
2021-04-28