使用 MySql 和 PHP 从具有多行的列中提取两个值
Extracting two values from a column with many rows with MySql and PHP
好的,所以我无法想出最大化此查询的方法。这是一个非常大的 table,所以我不想编写多个查询来获取这些值。这就是我的 table 的设置方式(无法更改)。
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
一行。如果每个时间类型和员工可能有多个匹配项,那么您可能需要另一个聚合函数而不是 max()
:想到 sum()
。
好的,所以我无法想出最大化此查询的方法。这是一个非常大的 table,所以我不想编写多个查询来获取这些值。这就是我的 table 的设置方式(无法更改)。
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
一行。如果每个时间类型和员工可能有多个匹配项,那么您可能需要另一个聚合函数而不是 max()
:想到 sum()
。