MySQL计算一个表的百分比

时间:2016-06-05 17:54:23

标签: mysql sql spring hibernate

我需要计算前20名失败用户的百分比,需要在春季java中使用hibernate。

+--------------+--------+------------+
| id  | result | code  |  techUser_id
+--------------+--------+------------+
| 1   | fail   | 23442 |  2
| 2   | fail   | 56432 |  5
| 3   | fail   | 98745 |  2
| 4   | fail   | 65478 |  5
| 5   | fail   | 36448 |  2
| 6   | fail   | 87745 |  5
+--------------+--------+------------+

预期输出:排名前20的列表失败,每个用户的记录总数的最大百分比

我不确定查询应该是什么,所以请帮我找到解决方案。

我拥有的东西,我知道它不正确: -

select techUser_id, count( * ),(SELECT COUNT( * )  from inspection) * 100 ,
count( * )/(SELECT COUNT( * )  from inspection) * 100 as perc
 from inspection
 where techUser_id != ''
 and inspectionResult ='FAIL'
 group by techUser_id
 order by  perc limit 20;

获得此结果

enter image description here

谢谢

执行此查询以进行检查

select techUser_id, result, count(*) num
from inspection 
group by techUser_id, result
order by num

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT techUser_id, COUNT(*) AS Total , (COUNT(*) / (SELECT COUNT(*)
FROM inspection WHERE result='fail')) * 100 AS 'list of top 20 failed with max', 
FROM inspection
WHERE result='fail'
GROUP BY techUser_id;

答案 1 :(得分:0)

 select techUser_id, count(*),(SELECT COUNT(*)  from inspection) * 100 ,   count(*)/(SELECT COUNT(*)  from inspection) * 100 as perc 
 from inspection 
 where techUser.id != '' 
 and result ='FAIL' 
 group by techUser_id 
 order perc limit 20;

执行此查询以进行检查

select techUser_id, result, count(*) num
from inspection 
group by techUser_id, result
order by num