【问题标题】:Get a percentage in a pivot mysql query在透视 mysql 查询中获取百分比
【发布时间】:2021-01-29 13:10:36
【问题描述】:

我的数据看起来像

 EmployeeId      paycategory            value

      1             Contribution         200
      1              Salary              18000

我使用以下查询,

select employeeid,
    max(case when paycategory = 'Salary'       then value end) salary,
    max(case when paycategory = 'Contribution' then value end) contribution
from reports
group by employeeid

上面显示的结果为,

EmployeeId        Salary      Contribution
      1             18000           200

这很棒。现在我想显示贡献对工资的百分比

所以我期待类似的东西,

EmployeeId        Salary      Contribution      Contribution Percentage
      1             18000           200            1.11 -- (200/18000)*100

如果可能的话,我该如何使用数据透视查询?

【问题讨论】:

  • 考虑处理应用代码中数据显示的问题

标签: mysql aggregate common-table-expression mysql-8.0


【解决方案1】:

你可以像下面这样使用子查询:

select 
employeeid, 
salary, 
contribution, 
(contribution/salary)*100 Contribution_Percentage 
from (
select employeeid,
    max(case when paycategory = 'Salary'       then value end) salary,
    max(case when paycategory = 'Contribution' then value end) contribution
from reports
group by employeeid 
) t

DEMO on Fiddle

对于 MySql 8.0,您可以使用 Common Table Expression,如下所示:

with cte as (
select employeeid,
    max(case when paycategory = 'Salary'       then value end) salary,
    max(case when paycategory = 'Contribution' then value end) contribution
from reports
group by employeeid 
)
select 
employeeid, 
salary, 
contribution, (contribution/salary)*100 Contribution_Percentage
from cte

DEMO

【讨论】:

  • 你可以使用它,也可以不用as写它。请检查小提琴
猜你喜欢
  • 1970-01-01
  • 2021-11-25
  • 2019-08-12
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多