我有一张费用表:
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版)
发布于 2019-09-01 19:04:44
您可以使用聚合函数和窗口函数:
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;https://stackoverflow.com/questions/57745416
复制相似问题