检查连续12周的0销售额

时间:2015-11-05 17:49:55

标签: sql netezza

我有一张包含customer_number,周和销售额的表格。我需要检查每个客户是否连续12周没有销售,并创建一个0/1的标志。

我可以查看过去12周或某段时间,但检查连续跑步的最佳方法是什么?这是我到目前为止的代码:

select * from weekly_sales 
 where customer_nbr in (123, 234)
 and  week < '2015-11-01'
 and week > '2014-11-01'
 order by customer_nbr, week
;

2 个答案:

答案 0 :(得分:2)

<强> Sql Fiddle Demo

这是简化版,只需要week_idsales

SELECT S1.weekid start_week, MAX(S2.weekid) end_week, SUM (S2.sales)
FROM Sales  S1
JOIN Sales  S2 
  ON  S2.weekid BETWEEN S1.weekid and S1.weekid + 11
WHERE S1.weekid BETWEEN 1 and 25     -- your search range
GROUP BY S1.weekid

让我知道你的工作是否合适

<强>输出

| start_week | end_week |    |
|------------|----------|----|
|          1 |       12 | 12 |
|          2 |       13 |  8 |
|          3 |       14 |  3 |
|          4 |       15 |  2 |
|          5 |       16 |  0 |   <- 
|          6 |       17 |  0 |   <- no sales for 12 week
|          7 |       18 |  0 |   <-
|          8 |       19 |  4 | 
|          9 |       20 |  9 |
|         10 |       21 | 11 |
|         11 |       22 | 15 |
|         12 |       23 | 71 |
|         13 |       24 | 78 |
|         14 |       25 | 86 | 
|         15 |       25 | 86 |    < - less than 12 week range
|         16 |       25 | 86 |    < - below this line
|         17 |       25 | 86 |   
|         18 |       25 | 86 |
|         19 |       25 | 86 |
|         20 |       25 | 82 |
|         21 |       25 | 77 |
|         22 |       25 | 75 |
|         23 |       25 | 71 |
|         24 |       25 | 15 |
|         25 |       25 |  8 |

您的最终查询应该

  HAVING SUM (S2.sales) = 0
     AND COUNT(*) = 12

答案 1 :(得分:1)

嗯......你可以在'周'和'周'之间使用,你也可以使用“count(列)”来提高性能。 所以你只需要比较结果是否大于0