使用MySQL查找传递的数字和百分比

时间:2017-03-03 12:51:19

标签: mysql sql aggregate

我有一张考试表,其中包含总数(参加考试的学生人数),失败(考试中失败的学生人数)和日期如下所示的详细信息

id key    value date
 1 total    400 2017-02-28
 2 failed   200 2017-02-28
 3 total    350 2017-02-27
 4 failed   180 2017-02-27
 5 total    500 2017-02-26
 6 failed   250 2017-02-26 
 7 total    600 2017-02-25 
 8 failed   200 2017-02-25
 9 total    400 2017-02-24 
10 failed   100 2017-02-24

我在MySQL中编写了许多聚合查询,但现在我需要使用单个查询来显示如下所示的结果。

我们如何从两行计算传递和传递的百分比?

id total failed passed passed percentage date
 1   400    200    200 50%               2017-02-28 
 2   350    180    170 48.57%            2017-02-27
 3   500    250    250 50%               2017-02-26
 4   600    200    400 66.67%            2017-02-25
 5   400    100    200 75%               2017-02-24

任何人都可以帮助我

2 个答案:

答案 0 :(得分:2)

E.g:

SELECT date
     , SUM(CASE WHEN attribute = 'total'  THEN value END) total
     , SUM(CASE WHEN attribute = 'failed' THEN value END) failed
     , SUM(CASE WHEN attribute = 'total'  THEN value END) - SUM(CASE WHEN attribute = 'failed' THEN value END) passed 
     , 100 - SUM(CASE WHEN attribute = 'failed' THEN value END) / SUM(CASE WHEN attribute = 'total' THEN value END) * 100 pct_passed
  FROM my_table 
 GROUP 
    BY date;

答案 1 :(得分:1)

假设date将行绑定在一起,您可以使用聚合:

select (@rn := @rn + 1) as id, total, failed, (total - failed) as passed,
       (1 - failed / total) as passed_rate
from (select , date,
             sum(case when key in ('total') then value else 0 end) as total,
             sum(case when key = 'failed' then value else 0 end) as failed
      from t
      group by date
     ) t cross join
     (select @rn := 0) params
order by date;