sql计算分组数据的百分比

时间:2017-09-18 12:30:37

标签: mysql sql

我有一张像这样的表X,

student ans_status question_id
 1        1          10
 2        -1         10
 3         1         10
 4         0          10
 1        -1         11
 2         1          11
 3         -1          11
 4         -2         11

预期o / p

 10   2/3
 11   1/3

等。 现在,我想要每个问题10的数据,如, 数量为1 /(每个问题的总数为1&1;和-1' s) 我试过这个,

select (select count(student_id) from X
        where question_id=10 and ans_status=1) / count(student_id)
from X
where question_id=10
group by ans_status
having ans_status in(1,-1).

我可以在嵌套查询中执行此操作,再次根据状态条件进行选择和分组,但有没有更好的方法呢? 请注意我想要表格中的所有问题

2 个答案:

答案 0 :(得分:1)

你可以这样做:

select question_id,
       avg(ans_status = 1)
from X
where ans_status in (1, -1)
group by question_id;

这使用MySQL功能,即布尔表达式在数字上下文中被视为整数。 "真"是1和" false"是0,所以平均值是真实的百分比。

如果您想独立使用这些值:

select question_id,
       sum(ans_status = 1), count(*)
from X
where ans_status in (1, -1)
group by question_id;

答案 1 :(得分:0)

使用GROUP BY计算每个question_id的计数,以使answer_id的计数为1或-1。

<强>查询

select t.`question_id`,
t.`count_1` / t.`total_count` as `new_col` from(
    select `question_id`,
    sum(case `ans_status` when 1 then 1 when -1 then 1 else 0 end) as `count_1`,
    count(*) as `total_count`
    from `your_table_name`
    group by `question_id`
)t;

<强> Find a demo here

相关问题