我有如下表 (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 的子查询。
提前致谢!
最佳答案
这应该可以完成工作:
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 的解决方案。
关于mysql - 需要没有自定义变量的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144213/