MySQL Query - getting missing records when using group-by

前端 未结 4 1907
心在旅途
心在旅途 2021-01-07 14:48

I have a query :

select score, count(1) as \'NumStudents\' from testresults where testid = \'mytestid\'
group by score order by score

4条回答
  •  猫巷女王i
    2021-01-07 15:13

    SQL is good at working with sets of data values in the database, but not so good at sets of data values that are not in the database.

    The best workaround is to keep one small table for the values you need to range over:

    CREATE TABLE ScoreValues (score int);
    INSERT INTO ScoreValues (score) 
      VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
    

    Given your comment that you define the max marks of a test in another table, you can join to that table in the following way, as long as ScoreValues is sure to have values at least as high or higher than the greatest test's max marks:

    SELECT v.score, COUNT(tr.score) AS 'NumStudents'
    FROM ScoreValues v 
      JOIN Tests t ON (v.score <= t.maxmarks)
      LEFT OUTER JOIN TestResults tr ON (v.score = tr.score AND t.testid = tr.testid)
    WHERE t.testid = 'mytestid'
    GROUP BY v.score;
    

提交回复
热议问题