dongle7882 2014-02-12 09:47
浏览 29
已采纳

MySQL计数值直到特定行

Apologies if I'm not explaining my situation in perfect detail as I'm not a native speaker. I'm sure this is fairly simple for most people, but I struggle with it. I'm using php/mysql.

Suppose I have a database as follows:

id   game   scorer
1     1      molly
2     1      sarah
3     1      angela
4     1      molly
5     2      jane
6     2      molly
7     2      sarah

How would I write a query to present the scorers for each game with the number of goals they have scored during the season up until that particular goal?

Example: 
Game 1: Molly (1st), Sarah (1st), Angela (1st), Molly (2nd)
Game 2: Jane (1st), Molly (3rd), Sarah (2nd)
  • 写回答

2条回答 默认 最新

  • drduh44480 2014-02-12 10:06
    关注
    CREATE TABLE goals
    (goal_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    ,game INT NOT NULL
    ,scorer VARCHAR(12) NOT NULL
    );
    
    INSERT INTO goals VALUES
    (1,1,'molly'),
    (2,1,'sarah'),
    (3,1,'angela'),
    (4,1,'molly'),
    (5,2,'jane'),
    (6,2,'molly'),
    (7,2,'sarah');
    
    
    SELECT game, GROUP_CONCAT(CONCAT(scorer,'(',rank,')')) scorers FROM 
    (
    SELECT x.game
         , x.scorer
         , COUNT(*) rank 
      FROM goals x 
      JOIN goals y 
        ON y.scorer = x.scorer 
       AND y.goal_id <= x.goal_id 
     GROUP 
        BY x.game,x.goal_id,x.scorer
    )n
    GROUP BY game;
    
    +------+--------------------------------------+
    | game | scorers                              |
    +------+--------------------------------------+
    |    1 | molly(1),sarah(1),angela(1),molly(2) |
    |    2 | jane(1),molly(3),sarah(2)            |
    +------+--------------------------------------+
    

    The subquery on its own will give the alternative display

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图