1

这是一个示例表:

quizzes

id    user_id    quiz_id    has_passed    attempts
1     101        201        0             5          
2     101        202        1             1
3     102        201        1             3
4     103        203        1             2

我有两个查询,我想将它们组合起来以获得失败的测验尝试次数。

第一个查询获取每个测验的所有尝试的总和:

SELECT quiz_id, SUM(attempts) as sum
FROM quizzes
GROUP BY quiz_id

第二个查询计算测验通过的次数:

SELECT quiz_id, COUNT(*) as count
FROM quizzes
WHERE has_passed =1
GROUP BY quiz_id

我想从总尝试中减去通过尝试的次数,以获得按 quiz_id 分组的失败尝试次数。

什么查询会给我一个看起来像这样的输出?

quiz_id    failed_attempts    
201        7
202        0
203        1

谢谢!

4

4 回答 4

5
SELECT quiz_id, SUM(attempts - has_passed) failed_attempts
FROM quizzes
GROUP BY quiz_id

输出

| QUIZ_ID | FAILED_ATTEMPTS |
-----------------------------
|     201 |               7 |
|     202 |               0 |
|     203 |               1 |

sqlfiddle

于 2013-03-05T20:58:14.323 回答
1

你可以写:

SELECT quiz_id,
       SUM(attempts) - COUNT(CASE WHEN has_passed = 1 THEN 1 END)
         AS failed_attempts
  FROM quizzes
 GROUP
    BY quiz_id
;
于 2013-03-05T20:59:16.933 回答
0

我想你正在寻找:

SELECT quiz_id, SUM(attempts) AS attempts, SUM(attempts-has_passed) AS failed_attempts
FROM quizzes
GROUP BY quiz_id
于 2013-03-05T21:00:23.513 回答
0

试试下面

选择 quiz_id, (sum(attempts) - count(*)) 作为测验中的失败尝试 Group by quiz_id

于 2013-03-05T21:00:52.377 回答