【问题标题】:mysql query to get percentage of certain field in a table?mysql查询以获取表中某些字段的百分比?
【发布时间】:2019-09-01 11:01:18
【问题描述】:

我有费用表:

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版)

【问题讨论】:

标签: mysql sql


【解决方案1】:

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

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 5.6版
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 2021-01-29
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
相关资源
最近更新 更多