mysql查询获取表中某些字段的百分比?

标签 mysql sql

我有费用表:

Expense(amount: Double, vendorId: Int, vendorType: Int)

我想创建一个 mysql 查询,它会给出每种供应商类型与特定供应商的百分比,例如:

vendorId   vendorType percentOfExpencesOfThisType    totalExpenses

假设我有 4 项费用:

Expense(amount: 30.0, vendorId: 3, vendorType: 1)
Expense(amount: 58.5, vendorId: 3, vendorType: 1)
Expense(amount: 47.0, vendorId: 3, vendorType: 7)
Expense(amount: 21.5, vendorId: 3, vendorType: 13)

所以表格看起来:

vendorId   vendorType percentOfExpencesOfThisType    totalExpenses
3               1                 50                       4
3               7                 25                       4
3               13                25                       4

我该怎么做? (不幸的是使用mysql版本5.6)

最佳答案

您可以使用聚合和窗口函数:

select vendorId, vendorType,
       100 * count(*) / sum(count(*)) over (partition by vendorId) as percentOfExpensesOfThisType,
       sum(count(*)) over (partition by vendorId) as totalExpenses
from expense
group by vendorId, vendorType;

从 MySQL 8+ 开始可以使用窗口函数。

在早期版本中,您将连接两个聚合查询:

select vendorId, vendorType,
       100 * vt.cnt / v.cnt as percentOfExpensesOfThisType,
       v.cnt as totalExpenses
from (select vendorId, vendorType, count(*) as cnt
      from expense
      group by vendorId, vendorType
     ) vt join
     (select vendorId, count(*) as cnt
      from expense
      group by vendorId
     ) v
     on vt.vendorId = v.vendorId;

关于mysql查询获取表中某些字段的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745416/

相关文章:

mysql - 如何在Mysql中查找相似命名的数据库

mysql 选择不适用于 varchar 字段

mysql - SQL 使用子查询仅列出唯一值

sql - MS Access - 如何增加不同表中的数字?

java - SQL 缩放 : should I try to minimize queries when having multiple OR column conditions?

mysql - 如何在没有死锁的情况下批量更新 InnoDB 表?

asp.net - 基于文件的数据库 asp.net

sql - 在 SQL 触发器中使用等号时遇到问题

mysql - XAMPP中配置tomcat出错

sql - 2 单表功能依赖