MySQL划分派生列

时间:2017-01-18 18:36:03

标签: mysql database sum division

如何划分MySQL选择中生成的列?我有两个数据库,一个有问题,一个有尝试。我想用尝试次数,incorrect_attempts和correct_attempts来提取特定问题的尝试数据。然后我想按尝试次数划分正确的尝试(最好是尝试次数大于0)。

以下是一个示例查询,但不起作用:

SELECT SUM(CASE WHEN qa.id > 0 THEN 1 ELSE 0 END) attempts, 
    SUM(CASE WHEN qa.correct = 1 THEN 1 ELSE 0 END) correct_attempts, 
    SUM(CASE WHEN qa.correct = 0 THEN 1 ELSE 0 END) incorrect_attempts,
    (100 * correct_attempts / attempts) percentage
FROM test_questions tq
LEFT JOIN question_attempts qa ON qa.question_id = tq.id
GROUP BY id

此外,如果我可以使用此功能,我可以使用什么功能将百分比返回到两个小数点?

以下是一些示例数据:

{
    "table": "question_attempts",
    "rows":
    [
        {
            "id": 1,
            "question_id": 1,
            "user_id": 8,
            "correct": 1,
            "created_at": "2017-01-13 12:17:42"
        },
        {
            "id": 2,
            "question_id": 1,
            "user_id": 8,
            "correct": 0,
            "created_at": "2017-01-13 12:17:32"
        }
    ],
    "table": "test_questions",
    "rows":
    [
        {
            "id": 1,
            "question": "..."
        }
    ]
}

我想要的结果应如下所示:

{
    "rows":
    [
        {           
            "attempts": 2,
            "correct_attempts": 1,
            "incorrect_attempts": 1,
            "percentage": 50.00,            
        }
    ]
}

0 个答案:

没有答案