4

我有一张products桌子和一张sales桌子,用来记录给定产品在每个日期售出的商品数量。当然,并不是所有的产品每天都有销售。

我需要生成一份报告,告诉我产品连续销售了多少天(从最近日期到过去)以及仅在这些天销售了多少商品。

我想告诉你到目前为止我已经尝试了多少事情,但唯一成功的(而且缓慢的、递归的)是我的应用程序内部的解决方案,而不是我想要的 SQL 内部的解决方案。

我还浏览了几个关于 SO 的类似问题,但我还没有找到一个可以让我清楚地了解我真正需要什么的问题。

我在这里设置了一个SQLFiddle来向您展示我在说什么。在那里你会看到我能想到的唯一查询,它没有给我我需要的结果。我还在那里添加了注释,显示查询的结果应该是什么。

我希望这里有人知道如何做到这一点。提前感谢您的任何评论!

弗朗西斯科

4

3 回答 3

3

http://sqlfiddle.com/#!2/20108/1

这是一个完成这项工作的存储过程

CREATE PROCEDURE myProc()
BEGIN
    -- Drop and create the temp table
    DROP TABLE IF EXISTS reached;
    CREATE TABLE reached (
    sku CHAR(32) PRIMARY KEY,
    record_date date,
    nb int,
    total int)
   ENGINE=HEAP;

-- Initial insert, the starting point is the MAX sales record_date of each product
INSERT INTO reached 
SELECT products.sku, max(sales.record_date), 0, 0
FROM products
join sales on sales.sku = products.sku
group by products.sku;

-- loop until there is no more updated rows
iterloop: LOOP
    -- Update the temptable with the values of the date - 1 row if found
    update reached
    join sales on sales.sku=reached.sku and sales.record_date=reached.record_date
    set reached.record_date = reached.record_date - INTERVAL 1 day, 
        reached.nb=reached.nb+1, 
        reached.total=reached.total + sales.items;

    -- If no more rows are updated it means we hit the most longest days_sold
    IF ROW_COUNT() = 0 THEN
        LEAVE iterloop;
    END IF;
END LOOP iterloop;

-- select the results of the temp table
SELECT products.sku, products.title, products.price, reached.total as sales, reached.nb as days_sold 
from reached
join products on products.sku=reached.sku;

END//

然后你只需要做

call myProc()
于 2013-04-26T07:25:16.843 回答
3

没有存储过程的纯 SQL 解决方案:小提琴

SELECT sku
     , COUNT(1) AS consecutive_days
     , SUM(items) AS items
FROM
(
  SELECT sku
       , items
       -- generate a new guid for each group of consecutive date
       -- ie : starting with day_before is null
       , @guid := IF(@sku = sku and day_before IS NULL, UUID(), @guid) AS uuid
       , @sku := sku AS dummy_sku
  FROM 
  (
    SELECT currents.sku
         , befores.record_date as day_before
         , currents.items
    FROM sales currents
      LEFT JOIN sales befores 
        ON currents.sku = befores.sku 
        AND currents.record_date = befores.record_date + INTERVAL 1 DAY
    ORDER BY currents.sku, currents.record_date
  )  AS main_join
    CROSS JOIN (SELECT @sku:=0) foo_sku
    CROSS JOIN (SELECT @guid:=UUID()) foo_guid
) AS result_to_group
GROUP BY uuid, sku

查询真的没那么难。通过 声明变量cross join (SELECT @type:=0) type。然后在选择中,您可以逐行设置变量值。模拟Rank函数是必要的。

于 2013-04-26T08:10:30.747 回答
-1
select
  p.*,
  sum(s.items) sales,
  count(s.record_date) days_sold
from
  products p
join
  sales s
  on
  s.sku = p.sku
where record_date between '2013-04-18 00:00:00' and '2013-04-26 00:00:00'
group by sku; 
于 2013-04-26T07:30:33.697 回答