将SumIfs Excel函数转换为MySQL

时间:2018-04-14 12:36:07

标签: mysql sql excel

Here is the solution in Excel with Data.

单元格G2“ReplenQty”中的公式为:

=SUMIFS(D:D,A:A,A2,B:B,B2,C:C,">=" & E2,C:C,"<=" &F2)

单元格H2“RpInVar”中的公式为:

=IF($A2<>$A1,ROUND(VAR(IF($A:$A=$A2,$G:$G)),2),0)

我在MySQL中试过这个:

SELECT DISTINCT 
Part, 
Customer, 
OrdDt,
OrdQty,
StartDate,
ReplenDate,
SUM(CASE WHEN Part = Part AND Customer = Customer AND OrdDt >= StartDate AND OrdDt <= ReplenDate THEN OrdQty ELSE 0 END) AS ReplenQty,
VARIANCE(CASE WHEN Part = Part AND Customer = Customer AND OrdDt >= StartDate AND OrdDt <= ReplenDate THEN OrdQty ELSE 0 END) AS RpInVar,
FROM 
BeforeReplenQty
GROUP BY 
Part, 
Customer, 
OrdDt, 
OrdQty, 
StartDate, 
ReplenDate;

问题是OrdQty和ReplenQty是相同的,RpInVar都是0。

1 个答案:

答案 0 :(得分:0)

此查询非常漫长而复杂,但正在进行此演示:http://sqlfiddle.com/#!9/3b3334/70

一项任务是在订单日期在开始日期和补货日期之间进行汇总。 然后得到部分是新的行与前一行相比。

查询的第一部分是获取方差,第二个子查询是获取Ordered数量的总和,而底部的子查询是获取部分列已更改的行。

select tab.Part,tab.Customer,tab.OrdDt,tab.OrdQty,tab.StartDate,tab.ReplenDate,tab.ReplenQty,
       case when sumtab.Rnk=1 then 
         (select variance(ReplenQty)
             from (select  sum(t1.OrdQty) as ReplenQty
                     from BeforeReplenQty t2 
               inner join BeforeReplenQty t1 
               where t2.part=t1.part and t2.customer=t1.customer
                 and t2.OrdDt between t1.StartDate and t1.ReplenDate 
               group by t1.Part,t1.Customer,t1.OrdDt,t1.OrdQty,t1.StartDate,t1.ReplenDate) t3) else 0 end as ReplenVar
from (
    select t1.*,sum(t1.OrdQty) as ReplenQty
     from BeforeReplenQty t2 
    inner join BeforeReplenQty t1 
    where t2.part=t1.part and t2.customer=t1.customer
      and t2.OrdDt between t1.StartDate and t1.ReplenDate 
    group by t1.Part,t1.Customer,t1.OrdDt,t1.OrdQty,t1.StartDate,t1.ReplenDate) tab
left join (select part,customer,orddt,rnk
from (
select t.part,t.customer,t.OrdDt,
@s:=CASE WHEN @c <> t.part THEN 1 ELSE @s+1 END AS rnk,
   @c:=t.part AS partSet
from (SELECT @s:= 0) s 
inner join (SELECT @c:= 'A') c 
inner join (SELECT * from BeforeReplenQty 
            order by Part, Customer, OrdDt) t
     ) tab
where rnk = 1
   ) sumtab
on tab.part=sumtab.part and tab.customer=sumtab.customer and tab.orddt=sumtab.orddt;