如何解决在枢轴mysql查询中获取百分比
我的数据看起来像
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 = 'Contribution' then value end) contribution
from reports
group by employeeid
)
select
employeeid,(contribution/salary)*100 Contribution_Percentage
from cte
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。