将 SumIfs Excel 函数转换为 MySQL
Posted
技术标签:
【中文标题】将 SumIfs Excel 函数转换为 MySQL【英文标题】:Convert SumIfs Excel Function to MySQL 【发布时间】:2018-04-14 12:36:07 【问题描述】:单元格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】:此查询相当长且复杂,但正在处理此演示:http://sqlfiddle.com/#!9/3b3334/70
其中一项任务是求和,其中订单日期介于开始日期和补货日期之间。 然后获取与前一行相比部分是新的行。
查询的第一部分是获取方差,第二个子查询是获取Ordered qty的总和,底部的子查询是获取part列发生变化的行。
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;
【讨论】:
当我运行上面的代码时,我得到错误代码:1267。操作''的排序规则(utf8_general_ci,IMPLICIT)和(utf8_unicode_ci,IMPLICIT)的非法混合以上是关于将 SumIfs Excel 函数转换为 MySQL的主要内容,如果未能解决你的问题,请参考以下文章