繁体   English   中英

在mysql查询中进行计算

[英]Doing Calculations in mysql query

我有一个user_answer表,其中包含类似这样的值。 基本上,我存储用户的响应。

userid   category_id    question_id  difficulty_level response    updated_date

1395           1             1              5            0        2014-08-29 00:29:48
1395           1             2              1            1        2014-08-30 11:29:34
1395           1             3              2            0        2014-08-25 08:12:28
1421           1             2              1            1        2014-08-25 06:32:45
1421           1             3              2            1        2014-08-28 01:25:24

响应

"0" is wrongly answered

"1" is answered correct

难度等级为1-5。 每个问题都有不同的难度级别(1,2,3,4,5)。

我想使用category_id计算每个用户的积分。 这是计算点数的方法(在PHP中)。

$cur_points = 0;
if(response == 1){
   $cur_points = $cur_points - 1;
}
else if(response == 0){
    if(difficulty_level== 1){
        $cur_points = $cur_points + 5;
    }
    else if(difficulty_level== 2){
        $cur_points = $cur_points + 4;
    }
    else if(difficulty_level== 3){
        $cur_points = $cur_points + 3;
    }
    else if(difficulty_level== 4){
        $cur_points = $cur_points + 2;
    }
   else if(difficulty_level== 5){
        $cur_points = $cur_points + 1;
    }
}

现在,此计算我必须自行执行MYSQL查询,结果应如下所示:

 userid   category_id   recently_answered_date           points

 1395           1       2014-08-30 11:29:34                 4
 1421           1       2014-08-28 01:25:24                 3

最近更新日期是用户在该类别中回答问题的最近日期。

有可能吗? 谢谢。

使用条件SUM来添加所需的值。

 SELECT user_id, 
        category_id,
        max(updated_date) as recently_answered_date,
        SUM( CASE response
                   WHEN 0 THEN -1
                   ELSE CASE difficulty_level
                             WHEN 1 THEN 5
                             WHEN 2 THEN 4
                             WHEN 3 THEN 3
                             WHEN 4 THEN 2
                             ELSE 1
                        END
             END) as POINTS
   FROM user_answer
   GROUP BY user_id, category_id

注意:尚不清楚为什么正确答案'1'删除查询中的点,所以我想那是错别字,无论是查询还是wrong/correct定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM