SQL查询 - 计算估计成本和实际成本

时间:2015-02-28 04:16:52

标签: mysql sql database

考虑具有以下结构和数据的两个表

Table 1

Task    Category    Estimated Cost
1       11          90.00
2       11          50.00
3       11          3.00
4       12          70.00
5       12          17.00
6       12          5.00
Table 2

Voucher     Task    Actual Cost
1           1       17.00
2           1       55.00
3           1       35.00
4           2       16.00
5           4       28.00
6           5       5.00
7           5       12.00
8           6       10.00

我需要一个查询,根据估算的成本和按类别的实际成本提供以下结果。

Result

Category    Estimated_Cost   Actual_Cost
11          143.00           123.00
12          92.00            55.00

2 个答案:

答案 0 :(得分:0)

您的问题是您必须分别计算每笔金额:

select category,
       sum(case when cost_type = 'estimated' then cost end) as estimated_cost,
       sum(case when cost_type = 'actual' then cost end) as actual_cost
  from (select t1.category,
               sum(t2.actual_cost) as cost,
               'actual' as cost_type
          from t1
          join t2
            on t1.task = t2.task
         group by t1.category
        union all
        select category, sum(estimated_cost), 'estimated'
          from t1
         group by category) x
 group by category

小提琴: http://sqlfiddle.com/#!5/33e08/1/0

答案 1 :(得分:0)

select
    e.Category,
    sum(e.`Estimated Cost`) as Estimated_Cost,
    min(a.`Actual Cost`) as Actual_Cost
from
    Table1 as e inner join
    (select Task, sum(`Actual cost`) as `Actual Cost` from Table2 group by Task) as a
        on a.Task = e.Task
group by e.Category