Search code examples
phpmysqlsumpivotsubquery

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. 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. Is the only real option to do two separate subqueries to get that information? Any help on how the query would look?


Solution

  • 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. If there may be multiple matches per time type and employee, then you probably need another aggregate function than max(): sum() comes to mind.