如何计算特定id的两个不同值?

of1yzvn4  于 2021-06-23  发布在  Mysql
关注(0)|答案(4)|浏览(277)

这个问题在这里已经有答案了

如何在mysql中返回pivot表输出(9个答案)
两年前关门了。
所以我有一个表格,里面有我做的测验的数据。为什么?这样我就可以找出成功率特别高/低的问题,以确定是否需要改写某个问题。我想它会派上用场的=)不管怎样,我在把答案“分组”到一行,以及计算“正确”和“错误”的出现次数方面遇到了一些麻烦。
表如下所示:

+----+---------+----------+-------------+---------+------------+------------+
| id | user_id | stack_id | question_id | answer  | created_at | updated_at |
+----+---------+----------+-------------+---------+------------+------------+
|  1 |      34 |        1 |          45 | wrong   | NOW()      | NOW()      |
|  2 |      55 |        1 |          45 | correct | NOW()      | NOW()      |
|  3 |       2 |        3 |          13 | wrong   | NOW()      | NOW()      |
|  4 |      99 |        1 |          46 | correct | NOW()      | NOW()      |
|  5 |      12 |        3 |          13 | wrong   | NOW()      | NOW()      |
|  6 |      12 |        2 |          10 | correct | NOW()      | NOW()      |
+----+---------+----------+-------------+---------+------------+------------+

列名正确,数据是实体模型。但我想把所有的 question_id s、 数一数有多少 wrong 有多少 correct 存在于此 question_id .
(我不是sql的家伙,所以请,如果有其他方式显示此数据,请随意!)
但预期的结果应该是:

+----------+-------------+-------+---------+
| stack_id | question_id | wrong | correct |
+----------+-------------+-------+---------+
|        1 |          45 |     1 |       1 |
|        3 |          13 |     1 |       0 |
|        1 |          46 |     0 |       1 |
|        2 |          10 |     0 |       1 |
+----------+-------------+-------+---------+

到目前为止,这就是我所拥有的,而且并不多: SELECT answer, COUNT(*) FROM answers GROUP BY answer ,它似乎也显示了错误的信息。

pb3skfrl

pb3skfrl1#

如果这是mysql,我将使用以下逻辑:

select stack_id, question_id,
       sum(answer = 'correct') as correct, sum(answer = 'wrong') as wrong
from t
group by stack_id, question_id;
umuewwlo

umuewwlo2#

试试这个:

select stack_id,question_id,sum(case when answer='wrong' then 1 else 0 end) as wrong,
           sum(case when answer='correct' then 1 else 0 end) as correct
    from your_table
    group by stack_id,question_id;

让我知道它是否有效。

3bygqnnd

3bygqnnd3#

您可以使用以下sql来获得所需的结果:

select stack_id,question_id,
sum(case when answer='wrong' then 1 else 0 end) as wrong,
sum(case when answer='correct' then 1 else 0 end) as correct
from your_table_name
group by stack_id,question_id;
yfjy0ee7

yfjy0ee74#

SELECT
    Answer
    , QuestionID
    , Count(Answer)
GROUP BY
   Answer, 
   QuesitonID

相关问题