mySQL中每个子查询的最大值

时间:2016-09-12 09:09:11

标签: mysql sql subquery

我使用下面提到的查询来获取差异和百分比变化>成本中心,供应商和工具两个季度之间的30个。输出类似于Costcenter,供应商和工具:enter image description here

我希望获得一个结果,该结果将为成本中心提供最大差异,然后是该供应商的最大供应商和该供应商的最大工具,例如,对于costcenter A,供应商c是最大值,供应商c max工具是4。

enter image description here

我正在使用的查询是:

select ccv.Costcenter,
       (cc.sumq3 - cc.sumq2) as costcenter_diff, ((((cc.sumq3 - cc.sumq2)/cc.sumq2)*100) ) as Costcenter_change, ccv.Vendor,
       (ccv.sumq3 - ccv.sumq2) as venor_diff, ((((ccv.sumq3 - ccv.sumq2)/ccv.sumq2)*100)) as Vendor_change, ccvt.Tool,(ccvt.sumq3 - ccvt.sumq2) as Tool_diff,((((ccvt.sumq3 - ccvt.sumq2)/ccvt.sumq2)*100)) as Tool_Change
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 Glm_Test.CostCenter_Rawdata
      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 Glm_Test.CostCenter_Rawdata
      where quarter in ('15/16 Q3', '15/16 Q2')
      group by Costcenter, Vendor
     ) ccv join
     (select Costcenter, Vendor,Tool,
             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 Glm_Test.CostCenter_Rawdata
      where quarter in ('15/16 Q3', '15/16 Q2')
      group by Costcenter, Vendor,Tool
     ) ccvt
     on cc.Costcenter = ccv.Costcenter and ccv.Vendor=ccvt.Vendor and cc.Costcenter = ccvt.Costcenter
    Having  Costcenter_change > 30  and Vendor_change > 30 and tool_change >30  ;

1 个答案:

答案 0 :(得分:0)

供应商是最大的是什么意思?他有成本中心的最大销售额?

我建议您使用分区来查找最大值,也可以使用它而无需连接数据三次。

例如使用:

RANK() OVER (PARTITION BY Costcenter ORDER BY sumq3-sumq2)

对于成本中心,sumq3和sumq2将是脚本中案例的总和。

RANK() OVER (PARTITION BY Costcenter,Vendor ORDER BY sumq3-sumq2)

供应商等。

然后从该输出中选择仅所有三个等级为1的位置。

您还需要为相应的sumq3和sumq2执行列以了解分区结果。

我希望有所帮助。

编辑:试试这个:

with costs as
(     
select Costcenter,
Vendor,
Tool,
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 Glm_Test.CostCenter_Rawdata
where quarter in ('15/16 Q3', '15/16 Q2')
group by Costcenter,Vendor,Tool
)
select Costcenter,sum(sumq3)-sum(sumq2) over (partition by Costcenter)     as Costcenter_diff
Vendor,sum(sumq3)-sum(sumq2) over (partition by Costcenter,Vendor) as     Vendor_diff,
Tool,sum(sumq3)-sum(sumq2) over (partition by Costcenter,Vendor,Tool) as     Tool_diff
   from costs