在表上连接多个查询并获得单个选择结果

时间:2016-09-10 11:53:18

标签: mysql sql subquery

我有一个包含Costcenter,Vendor,Tool,cost和quarter列的表格。我想得到两个季度之间的成本差异的结果(比如Q3 15/16和Q2的15/16):

enter image description here

我创建了查询,以便最初获得Costcenter和Vendor的结果,如下所示,但它没有正确加入两个: enter image description here

select a.Costcenter,c.Vendor,(SumA-SumB) as costcenter_diff, (SumC-SumD) as vendor_diff from
    (select Costcenter ,sum(CostTotal) as SumA
                  from Rawdata
                  where Quarter='15/16 Q3'
                  group by Costcenter)as a,
                  (select Costcenter,sum(CostTotal) as SumB
                  from Rawdata
                  where Quarter='15/16 Q2'
                  group by Costcenter) as b
     Join 
    (select Costcenter,Vendor,sum(CostTotal) as SumC
                  from Rawdata
                  where Quarter='15/16 Q3'
                  group by Costcenter,Vendor)as c,
                  (select Costcenter,Vendor,sum(CostTotal) as SumD
                  from Rawdata
                  where Quarter='15/16 Q2' 
                  group by Costcenter,Vendor) as d where a.Costcenter = b.Costcenter and  
                  c.Costcenter= d.Costcenter and c.Vendor= d.Vendor;

1 个答案:

答案 0 :(得分:0)

首先,使用条件聚合。例如:

select CostCenter,
       sum(case when quarter = '15/16 Q2' then costtotal else 0 end) as sumq2,
       sum(case when quarter = '15/16 Q3' then costtotal else 0 end) as sumq3
from rawdata rd
where quarter in ('15/16 Q3', '15/16 Q2');

然后,为供应商执行此操作并将它们连接在一起:

select ccv.costcenter, ccv.vendor,
       (cc.sumq3 - cc.sumq2) as cc_diff,
       (ccv.sumq3 - ccv.sumq2) as ccv_diff
from (select CostCenter,
             sum(case when quarter = '15/16 Q2' then costtotal else 0 end) as sumq2,
             sum(case when quarter = '15/16 Q3' then costtotal else 0 end) as sumq3
      from rawdata rd
      where quarter in ('15/16 Q3', '15/16 Q2')
      group by CostCenter
     ) cc join
     (select CostCenter, vendor,
             sum(case when quarter = '15/16 Q2' then costtotal else 0 end) as sumq2,
             sum(case when quarter = '15/16 Q3' then costtotal else 0 end) as sumq3
      from rawdata rd
      where quarter in ('15/16 Q3', '15/16 Q2')
      group by CostCenter, vendor
     ) ccv
     on cc.costcenter = ccv.costcenter;

注意:

  • 将列命名为合理的。 ab只是不容易理解查询。
  • JOIN条件应该在ON条款中,而不是WHERE条款。
  • 从不FROM子句中使用逗号。 始终使用明确的JOIN语法。