简体   繁体   English

使用 MySql 和 PHP 从具有多行的列中提取两个值

[英]Extracting two values from a column with many rows with MySql and PHP

Alright, so I'm having trouble coming up with a way to maximize this query.好吧,所以我在想出一种最大化此查询的方法时遇到了麻烦。 This is a very large table, so I don't want to write multiple queries to get these values.这是一个非常大的表,所以我不想编写多个查询来获取这些值。 This is how my table is set up (can't change it).这就是我的桌子的设置方式(无法更改)。

    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

So if you imagine thousands of rows with many entries for each employee.因此,如果您想象数千行,每个员工都有很多条目。 There are numerous rows with the ST and OT time_types. ST 和 OT time_types 有很多行。 I want the results to come out like我希望结果像

   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

I can handle writing a query grouping by and summing up the St hours, ot hours, and revenue, what I'm having trouble with is getting the st bill rate and ot bill rate.我可以处理编写查询分组并汇总 St 小时、ot 小时和收入,我遇到的问题是获取 st 账单费率和 ot 账单费率。 Is the only real option to do two separate subqueries to get that information?执行两个单独的子查询来获取该信息是唯一真正的选择吗? Any help on how the query would look?关于查询的外观有什么帮助吗?

You can use conditional aggregation:您可以使用条件聚合:

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

Note that this assumes one row per time_type for each employee.请注意,这假设每个员工的每个time_type一行。 If there may be multiple matches per time type and employee, then you probably need another aggregate function than max() : sum() comes to mind.如果每个时间类型和员工可能有多个匹配项,那么您可能需要另一个聚合 function 而不是max() :想到sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM