mysql - 根据行数与行数除以where条件的结果对所有记录进行排序

标签 mysql sqlite

下面是我正在使用的表格。

enter image description here

我想做的是获取每个 emp_id 的总行数作为 total_count,然后获取每个 emp_id 的总行数,其中 tos >0 作为 total_eligible,然后按 total_eligible/total_count 对它们进行排序。

Here's the fiddle I am working with.

最佳答案

您可以使用条件聚合来做到这一点:

select emp_id, count(*) as total,
       sum(case when tos > 0 then 1 else 0 end) as total_eligible,
       avg(case when tos > 0 then 1.0 else 0 end) as total_eligible_ratio
from table t
group by emp_id
order by total_eligible * 1.0 / total;

Here是一个 SQL fiddle 。

关于mysql - 根据行数与行数除以where条件的结果对所有记录进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814730/

相关文章:

mysql - 如何在查询中对 GROUP BY 的结果进行分组?

php - 近交免疫数据库结构

php - MySQL的英文单词数据库?

mysql - 运行EXPLAIN时,如果key的字段值不为null,Extra为空,是否使用了key?

ios - JSON 到核心数据 SQLITE 错误

android - 类型干扰失败。 Kotlin 和 Anko 中的预期类型不匹配 : required String found pair<String, String>

php - 这个sql IF语句是如何工作的?

python - 为什么这不起作用(sqlite,python)

.net - 如何在 Visual Studio 2008 中从现有 SQLite 数据库创建 Entity Framework 模型?

java - 请求异常索引 1,大小为 1