如何列出重复项目中的行号

时间:2019-04-28 16:35:11

标签: mysql sql mariadb

我正在做一个数据库报告,其中包含许多寄存器,但是某些条件有意排除了其中一些寄存器。我想在排除无效寄存器后添加带有行号的列,并且此计数器仅在重复玩家和Mission_id时才应递增。即:

Expected result

我正在运行MariaDB 10.1(我不能使用ROW_NUMBER),我有两个查询,第一个可以与counter很好地工作,第二个是报表查询,但是我不知道如何“合并”这个查询或在报告中获取该计数器列。

我尝试使用用户变量,但这会设置意外的值,并且不起作用。

第一个查询:

SET @ATT = 0;
SET @PREV = NULL;

SELECT
    attempts.id,
    players.id AS player,
    attempts.mission_id,
    @ATT := CASE WHEN CONCAT(players.id,attempts.mission_id) = @PREV THEN @ATT+1 ELSE 1 END AS COUNTER,
    @PREV := CONCAT(players.id,attempts.mission_id) AS PREV
FROM
    attempts
    INNER JOIN matches ON attempts.match_id = matches.id
    INNER JOIN players ON matches.player_id = players.id
WHERE TIMESTAMPDIFF( SECOND, attempts.started_at, attempts.finished_at ) > 90 AND players.deleted_at IS NULL
ORDER BY players.id, attempts.id

第二个查询(报告):简短版本

SET @SQL = CONCAT( 'SELECT
    players.id,
    missions.`name` AS mission,
    @ATT := CASE WHEN CONCAT(players.id,missions.id) = @PREV THEN @ATT+1 ELSE 1 END AS COUNTER,
    @PREV := CONCAT(players.id,missions.id) AS prev,
    attempts.try AS attempt,
TIMESTAMPDIFF( SECOND, attempts.started_at, attempts.finished_at ) AS "attempt duration"
    FROM attempts
    INNER JOIN missions ON attempts.mission_id = missions.id
    INNER JOIN matches ON attempts.match_id = matches.id
    INNER JOIN players ON matches.player_id = players.id
    WHERE TIMESTAMPDIFF( SECOND, attempts.started_at, attempts.finished_at ) > 90 AND players.deleted_at IS NULL
    GROUP BY attempts.id
    ORDER BY players.id, attempts.id' );

这是报告的输出:

Current output

COUNTER返回4而不是预期的2,我也不想在报告中也有该prev列。

0 个答案:

没有答案