我有下面的表格(my_table)
Sku | Date | Quantity
a | 2014-01-21 | 1
a | 2014-01-20 | 1
a | 2014-01-19 | 3
a | 2014-01-18 | 1
a | 2014-01-17 | 5
a | 2014-01-16 | 1
a | 2014-01-15 | 1
a | 2014-01-14 | 2
a | 2014-01-13 | 1
a | 2014-01-12 | 1
如果数量总和> = 10则需要获得相应的日期。我的意思是需要执行每一行并同时对数量求和,当数量达到大于或等于10时,从那一行得到相应的日期。
从上表中我的输出日期应为“2014-01-17”。
我已经用自定义变量编写了脚本(如下所示)。工作正常。
SET @qnty := NULL;
SELECT @d AS Date FROM (
SELECT Quantity,
@qnty := IF(@qnty IS NULL, Quantity, @qnty+Quantity),
@d := IF(@qnty >= 10, Date, @d)
FROM `my_table`
WHERE Quantity > 0
AND `Sku` = 'a'
ORDER BY Date DESC LIMIT 10
) a
LIMIT 1
但是我需要一个没有自定义变量的查询,因为我需要将此查询用作另一个VIEW的子查询。
提前致谢!
答案 0 :(得分:0)
这应该做的工作:
select
my_table.sku,
my_table.dt
from my_table
where
(select sum(my_table2.Quantity) from my_table as my_table2
where my_table2.sku = my_table.sku and
my_table2.dt >= my_table.dt) >= 10
and
coalesce((select sum(my_table2.Quantity) from my_table as my_table2
where my_table2.sku = my_table.sku and
my_table2.dt > my_table.dt), 0) < 10
这是fiddle。
修改:改进了管理多个SKU的解决方案。