MySQL-对行进行计数,直到达到第一个不同的值

时间:2019-02-19 13:51:46

标签: mysql sql

我正在尝试为每个不同的值计算直到首次出现不同的值为止的行数。

表格示例

game winner
-----------
1    Mark
2    Joe
3    Mark
4    Paula
5    Paula
6    Paula
7    Joe
8    Anna

在下面的查询中,我明白了。

SELECT winner,COUNT(*) as count FROM tablename GROUP BY winner;

结果

Mark won 2 games
Joe won 2 games
Paula won 3 games
Anna won 1 game

以下是我想要获得的结果:

Mark won 2 games, but didn't won last 6 games 
Joe won 2 games, but didn't won last 1 games 
Paula won 3 games, but didn't won last 2 games 
Anna won 1 game, but didn't won last 0 games

谢谢您抽出宝贵的时间来帮助我,我真的很感激。

3 个答案:

答案 0 :(得分:1)

您可以在相关子查询中计算最近未赢的游戏。

select winner, count(*) as won, (
  select count(*)
  from tablename t2
  where t2.game > max(t1.game)
) as not_won
from tablename t1
group by winner

演示:https://www.db-fiddle.com/f/czHPqscvEGgLPLeVYHV5hk/0

答案 1 :(得分:1)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(game SERIAL PRIMARY KEY
,winner VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,'Mark'),
(2,'Joe'),
(3,'Mark'),
(4,'Paula'),
(5,'Paula'),
(6,'Paula'),
(7,'Joe'),
(8,'Anna');

SELECT x.winner 
     , y.total
     , COUNT(z.game) games_since_last_win
  FROM my_table x 
  JOIN 
     ( SELECT COUNT(game) total
            , MAX(game) game 
         FROM my_table 
        GROUP 
           BY winner
     ) y 
    ON y.game = x.game
  LEFT
  JOIN my_table z
    ON z.winner <> x.winner
   AND z.game > x.game
 GROUP   
    BY x.winner;
+--------+-------+----------------------+
| winner | total | games_since_last_win |
+--------+-------+----------------------+
| Anna   |     1 |                    0 |
| Joe    |     2 |                    1 |
| Mark   |     2 |                    5 |
| Paula  |     3 |                    2 |
+--------+-------+----------------------+

答案 2 :(得分:0)

我的答案基于this one

我将按照游戏的降序对它进行排序并对其进行排名,然后将查询围绕该游戏进行包装。

为了避免混淆,我将COUNT(*) as count更改为COUNT(*) as cntcount是一个SQL关键字

模式(MySQL v5.7)

CREATE TABLE test (
  `game` INTEGER,
  `winner` VARCHAR(5)
);

INSERT INTO test
  (`game`, `winner`)
VALUES
  (1, 'Mark'),
  (2, 'Joe'),
  (3, 'Mark'),
  (4, 'Paula'),
  (5, 'Paula'),
  (6, 'Paula'),
  (7, 'Joe'),
  (8, 'Anna');

查询#1

SELECT winner, COUNT(*) as cnt, MIN(rank) AS lastwon FROM
(
    SELECT    winner,
              game,
              @curRank := @curRank + 1 AS rank
    FROM      test, (SELECT @curRank := -1) r
    ORDER BY  game DESC
 ) ranking
 GROUP BY winner
 ORDER BY cnt;

输出

| winner | cnt | lastwon |
| ------ | --- | ------- |
| Anna   | 1   | 0       |
| Joe    | 2   | 1       |
| Mark   | 2   | 5       |
| Paula  | 3   | 2       |

View on DB Fiddle