mysql查询以获取表中特定字段的百分比?
我有一份费用表:mysql查询以获取表中特定字段的百分比?,mysql,sql,Mysql,Sql,我有一份费用表: Expense(amount: Double, vendorId: Int, vendorType: Int) 我想创建一个mysql查询,该查询将为我提供特定供应商的每种供应商类型的百分比,如: vendorId vendorType percentOfExpencesOfThisType totalExpenses 假设我有4项费用: Expense(amount: 30.0, vendorId: 3, vendorType: 1) Expense(amoun
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 5.6版时,您应该阅读@P.Salmon谢谢,我会阅读的。