mysql摘要列使用嵌套查询

时间:2019-02-21 19:21:13

标签: mysql

我需要一条select语句来返回不同的摘要列。

这是基本结构:

lat = 12.13

lon =  5.02

所以样本返回行看起来像...

Column 1: Date
Column 2: Owner
Column 3: Sum of "Hours" where "Status" = 'billable'
Column 4: Sum of "Hours" where "Status" = 'non billable'

这是我的代码。它会返回整个日期范围内所有所有者的小时数,而不是按所有者的日期。

Date | Owner | Billable | Non Billable
2019-01-01 Bob Smith 17.54 13.66
2019-01-01 Joe Johnson 23.17 16.54

2 个答案:

答案 0 :(得分:0)

您的子查询按日期,所有者分组,并且您有总计。 对于Obtaion,按Date摸索的总和,所有者,您可以使用条件总和直接

    SELECT Date, Owner, 
        sum(case when Status = 'Billable' then Hours else 0 end) `Billable`
        sum(case when Status = 'Non Billable' then Hours else 0 end) `Non Billable`
     FROM timesheets
    WHERE Date between '2019-01-01' AND '2019-02-20'
    GROUP BY Date, Owner
    ORDER BY Date, Owner

答案 1 :(得分:0)

您不需要子查询。由于是求和,因此可以对CASE WHEN使用条件。如果条件匹配,则放置Hours,否则使用0,这对求和没有影响。检查以下解决方案:

SELECT "Date", "Owner",
   sum(case when Status = 'Billable' then Hours else 0 end) billable,
   sum(case when Status = 'Non Billable' then Hours else 0 end) non_billable
 FROM timesheets
WHERE "Date" between '2019-01-01' AND '2019-02-20'
GROUP BY "Date", "Owner"
ORDER BY "Date", "Owner"