在数据透视 mysql 查询中获取百分比
Get a percentage in a pivot mysql query
我的数据看起来像
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
如果可能,我该如何使用数据透视查询来解决这个问题?
您可以像下面这样使用子查询:
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
对于 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
我的数据看起来像
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
如果可能,我该如何使用数据透视查询来解决这个问题?
您可以像下面这样使用子查询:
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
对于 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