Mysql sql计算分组数据的百分比

Mysql sql计算分组数据的百分比,mysql,sql,Mysql,Sql,我有一张像这样的桌子 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

我有一张像这样的桌子

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的总数) 我试过这个

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).
我可以在嵌套查询中完成这项工作,方法是再次根据状态条件进行选择和分组,但是有更好的方法吗?
请注意,对于表中的所有问题,我希望使用
GROUP BY
计算每个
question\u id
以获得
答案\u 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;

您只需执行以下操作:

select question_id,
       avg(ans_status = 1)
from X
where ans_status in (1, -1)
group by question_id;
这使用了MySQL特性,即布尔表达式在数值上下文中被视为整数。“真”是
1
,“假”是
0
,所以平均值就是真的百分比

如果要独立地获取这些值,请执行以下操作:

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

使用该表数据,预期结果是什么?(表格格式。)在WHERE子句中放置正则列条件。HAVING子句用于聚合函数条件。很抱歉,我忘了添加,ANSU状态还有其他状态,如-2等,但我只对1和-1感兴趣,这就是为什么我使用group by而不是USE CONCAT W(“/”,t.
count_1
,t.
total_count
)作为
new\u col
生成百分比列作为x/y@Bhargav:我已经更新了我的答案。请检查它。这不起作用,因为计数(*)对问题10给出了4(3 1和1 0),因为我只想要3。它起作用,但你能解释一下,avg(ans_status=1)做什么?