[英]Extracting two values from a column with many rows with MySql and PHP
好吧,所以我在想出一种最大化此查询的方法时遇到了麻烦。 这是一个非常大的表,所以我不想编写多个查询来获取这些值。 这就是我的桌子的设置方式(无法更改)。
Table Name: job_hours
employee | job_title | bill_rate | hours | revenue | time_type
JOHN DOE---ENGINEER----120.5-------8--------960--------ST
JOHN DOE---ENGINEER----180.0-------4--------720--------OT
JANE DOE---SPECIALIST--96.0--------8--------768--------ST
因此,如果您想象数千行,每个员工都有很多条目。 ST 和 OT time_types 有很多行。 我希望结果像
EMPLOYEE---JOB TITLE---ST HOURS---OT HOURS---ST Bill Rate---OT Bill Rate---Revenue
JOHN DOE----ENGINEER------8---------4----------120.5-----------180----------1680
JANE DOE----SPECIALIST----8---------0----------96.0------------0.0----------768
我可以处理编写查询分组并汇总 St 小时、ot 小时和收入,我遇到的问题是获取 st 账单费率和 ot 账单费率。 执行两个单独的子查询来获取该信息是唯一真正的选择吗? 关于查询的外观有什么帮助吗?
您可以使用条件聚合:
select employee, job_title,
max(case when time_type = 'ST' then hours end) st_hours,
max(case when time_type = 'OT' then hours end) ot_hours,
max(case when time_type = 'OT' then bill_rate end) ot_bill_rate,
max(case when time_type = 'ST' then bill_rate end) st_bill_rate,
sum(revenue) revenue
from mytable
group by employee, job_title
请注意,这假设每个员工的每个time_type
一行。 如果每个时间类型和员工可能有多个匹配项,那么您可能需要另一个聚合 function 而不是max()
:想到sum()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.