【问题标题】:Extracting two values from a column with many rows with MySql and PHP使用 MySql 和 PHP 从具有多行的列中提取两个值
【发布时间】:2020-10-07 21:34:39
【问题描述】:

好的,所以我无法想出最大化此查询的方法。这是一个非常大的表,所以我不想编写多个查询来获取这些值。这就是我的桌子的设置方式(无法更改)。

    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 hours、ot hours 和收入,我遇到的问题是获取 st bill rate 和 ot bill rate。做两个单独的子查询来获取该信息是唯一真正的选择吗?有关查询外观的任何帮助?

【问题讨论】:

    标签: php mysql sum pivot subquery


    【解决方案1】:

    您可以使用条件聚合:

    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()

    【讨论】:

    • 哇,账单费率的最大案例效果很好。谢谢!
    猜你喜欢
    • 2012-09-15
    • 2013-09-25
    • 2012-11-07
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2010-11-27
    • 2013-05-16
    • 2020-11-05
    相关资源
    最近更新 更多