繁体   English   中英

选择SUM(field)达到特定点的行ID-MySQL

[英]Select row id where SUM(field) reaches a specific point - MySQL

我试图使用“标准”订单表来查找特定客户购买一定数量商品的时间。

Order ID      Items      Client      Date
--------      -----      ------      ----

1             1          Fred        26/04/2012
2             3          John        25/04/2012
3             2          Fred        20/04/2012
4             5          Fred        18/04/2012
5             3          Fred        14/04/2012
6             4          Fred        10/04/2012

因此,我想知道从现在开始到现在为止,弗雷德购买的最后10件物品所涵盖的时间范围。

在这种情况下,我将尝试确定加在一起的订单ID 1、3、4和5将我带到(或刚过了)我的10个项目的目标总数,因此我要寻找的日期是14/04/2012。

有一个简单的解决方案吗?

根据您所拥有的,没有简单的方法可以做到这一点。

如果要跟踪订购了哪些项目,则可以加入“项目”表,以便每个项目有一行。 然后,您可以选择前十名。

select *
from Orders o
join OrderItems oi on oi.orderId = o.orderId
join Items i on i.itemId = oi.itemId
where o.Client = 'Fred'
order by o.Date
limit 10;

然后语法可能会有所不同,具体取决于您所使用的数据库( 更多信息 )。

解决此问题的一种方法是计算已购买商品的总运行量:

select 
  orders.*, 
  sum(
    select items 
    from orders as `inner` 
    where client = "Fred" and 
     `outer`.`date` <= `inner`.`date`
  ) as `Running total`
from orders as `outer`
where client = "Fred"
order by date desc;

请注意选择列表中的子查询,该子查询汇总了Fred在该日期或之后购买的商品数量。

输出应该是这样的:

Order ID      Items      Client      Date         Running total
--------      -----      ------      ----         -------------

1             1          Fred        26/04/2012     1
3             2          Fred        20/04/2012     3
4             5          Fred        18/04/2012     8
5             3          Fred        14/04/2012     11
6             4          Fred        10/04/2012     15

然后,从此结果中,您可以轻松地选择适当的行。

从我头顶上...

CREATE FUNCTION time_of_last(itemcount INT, custid VARCHAR(50))
RETURNS DATE
BEGIN
   DECLARE tally INT DEFAULT 0;
   DECLARE ondate DATE;
   DECLARE curritems IN DEFAULT 0;
   DECLARE cur1 CURSOR FOR SELECT t.items, t.orderdate FROM yourtable t
      WHERE customer=custid ORDER BY orderdate DESC;
   DECLARE CONTINUE HANDLER FOR NOT FOUND SET ondate = NULL;

   OPEN cur1;

   read_loop: LOOP
       FETCH cur1 INTO curritems, ondate;
       SET tally = tally+curritems;
       IF (tally>=itemcount) THEN
            LEAVE read_loop;
       END IF;
   END LOOP;

   CLOSE cur1;

   RETURN ondate;
END;

SELECT time_of_last(10, 'Fred');

注意:如果您要开始收集其他信息(例如订单集中的订单),那么Matt Fenwick的解决方案会更干净。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM