繁体   English   中英

计算项目并获得百分比

[英]Count items and get percentage

我尝试从2个表格计算项目的百分比。

表:

operation_systems
id   | title
1001 | Windows
1002 | Apple
1003 | Linux

sub_pref
sub_id | id   | user_id
1      | 1001 | 1
2      | 1001 | 2
3      | 1003 | 1
4      | 1003 | 2
5      | 1003 | 1
6      | 1003 | 2
7      | 1003 | 3
8      | 1003 | 4
9      | 1003 | 5
10     | 1002 | 5

使用以下查询:

SELECT operation_systems.id, operation_systems.title,
COUNT(sub_pref.id) AS count, ROUND( SUM( 100 ) / total ) AS percentage
FROM operation_systems
CROSS JOIN (SELECT COUNT( * ) AS total FROM operation_systems)x
LEFT JOIN sub_pref ON sub_pref.id = operation_systems.id
GROUP BY operation_systems.id
ORDER BY count DESC;

当前结果:

Apple   | 1 | 33%
Windows | 2 | 33%
Linux   | 7 | 33%

所需结果:

Apple   | 1 | 10%
Windows | 2 | 20%
Linux   | 7 | 70%

如何获得正确的百分比?

错误在于这部分代码:

SELECT COUNT( * ) AS total FROM operation_systems

这将为您提供operation_systems的总数,即3,而不是sub_pref中引用每个operation_system的行的总数。 结果,您获得了33%的百分比,因为您将100除以3了三倍。

如果您以相反的方式思考问题,则更容易解决此问题。 您当前正在从operation_systems中进行选择,然后从sub_pref将数据提取到查询中。 但是,您真正想做的是将数据汇总到sub_pref中,然后为每个结果取一个好记的名字,来自operation_systems。

我建议:

SELECT operation_systems.title,
       COUNT(sub_pref.id) AS COUNT,
       ROUND(COUNT(sub_pref.id) * 100 /
               (SELECT COUNT(*)
                FROM sub_pref)) AS percentage
FROM sub_pref
LEFT JOIN operation_systems ON operation_systems.id = sub_pref.id
GROUP BY sub_pref.id
ORDER BY COUNT DESC

我已经使用您提供的架构/数据和上述解决方案创建了一个sqlfiddle 只需点击“运行SQL”即可查看它是否有效。

尝试这个:

SELECT os.id, os.title, sp.num_sp, os_total.total, ((sp.num_sp / os_total.total) * 100)
FROM operation_systems os
JOIN (
    SELECT id as os_id, COUNT(*) as num_sp
    FROM sub_pref
    GROUP BY id
) sp ON os.id = sp.os_id
CROSS JOIN (
    SELECT COUNT(*) as total
    FROM sub_pref
) os_total

这是一个易于阅读的查询:

SELECT title, (COUNT(sub_pref.id) / t.total) * 100 AS percent
FROM operation_systems, sub_pref, (SELECT COUNT(*) AS total FROM sub_pref) t
WHERE operation_systems.id = sub_pref.id
GROUP BY sub_pref.id
ORDER BY percent

工作演示http : //sqlfiddle.com/#!2/ab661/3

实现它的另一种方法

select 
os.id,
os.title,
ROUND( ( cnt / ( select count(*) from sub_pref )*100) ) as percentage
from operation_systems os
inner join (
    select id,count(id) as cnt from sub_pref 
    group by id
)sp
on sp.id = os.id
group by os.id
order by os.title

http://sqlfiddle.com/#!2/4bc0b/21

暂无
暂无

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

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