我有以下2个数据集:
数据集A
Item Location Date X Y
A USA Sep 10(Current Week) 10 10
A USA Sep 17 15 20
A USA Sep 24 10 5
A Canada Sep 10(Current Week) 0 4
A Canada Sep 17 6 0
A Canada Sep 24 13 15
B USA Sep 10(Current Week) 10 50
B USA Sep 17 5 15
B USA Sep 24 15 20
数据集B:
Item Location Z
A USA 15
A Canada 0
B USA 25
我需要如下输出数据集:
O / P
Item Location Date Final_Column
A USA Sep 10 15
A USA Sep 17 20
A USA Sep 24 15
A Canada Sep 10 4
A Canada Sep 17 0
A Canada Sep 24 2
B USA Sep 10 65
B USA Sep 17 75
B USA Sep 24 80
计算如下:
For current week, Final Column = (Z - X) + Y ----> 1st week value
For 2nd week, Final Column = (1st week value - X) + Y ----> 2nd week value
For 3rd week, Final Column = (2nd week value - X) + Y ----> 3rd week value
以此类推...
Additionally, if value of Final Column < 0 then Final Column = 0.
如何在MySQL中实现这种计算?
谢谢。
答案 0 :(得分:0)
尝试一下。不确定语法。
select a.item, a.location, a.date,
@value = case when @item <> a.item or @location <> a.location then b.z - a.x + a.y
else
@value - a.x + a.y end final_column
from a inner join b on a.item = b.item and a.location = b.location,
(select @value := 0, @item := '', @location := '') x
order by a.item, a.location, a.date
0以下将输出为0:
select a.item, a.location, a.date,
@value = case when @item <> a.item or @location <> a.location then b.z - a.x + a.y
else
@value - a.x + a.y end temp_column,
@value = case when @value < 0 then 0 else @value end final_column
from a inner join b on a.item = b.item and a.location = b.location,
(select @value := 0, @item := '', @location := '') x
order by a.item, a.location, a.date
如果有临时列,请告诉我。