MySQL Query - getting missing records when using group-by

前端 未结 4 1881
心在旅途
心在旅途 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条回答
  •  礼貌的吻别
    2021-01-07 15:10

    The most obvious way would be to create a table named "Scores" and left outer join your table to it.

    SELECT s.score, COUNT(1) AS scoreCount
    FROM score AS s
    LEFT OUTER JOIN testScores AS ts
    ON s.score = ts.score
    GROUP BY s.score

    If you don't want to create the table, you could use

    SELECT
    1 as score, SUM(CASE WHEN ts.score = 1 THEN 1 ELSE 0 END) AS scoreCount,
    2 as score, SUM(CASE WHEN ts.score = 2 THEN 1 ELSE 0 END) AS scoreCount,
    3 as score, SUM(CASE WHEN ts.score = 3 THEN 1 ELSE 0 END) AS scoreCount,
    4 as score, SUM(CASE WHEN ts.score = 4 THEN 1 ELSE 0 END) AS scoreCount,
    ... 10 as score, SUM(CASE WHEN ts.score = 10 THEN 1 ELSE 0 END) AS scoreCount
    FROM testScores AS ts

提交回复
热议问题