首页 > 解决方案 > 计算产品连续销售的总次数 - Sybase IQ

问题描述

我正在使用 Sybase IQ,从我的数据集中,我需要计算销售连续 10 件商品的总次数。

请查看数据集。

Product Date        Sale
Jams    2020-01-05  10
Jams    2020-01-06  10
Jams    2020-01-07  10
Jams    2020-01-08  10
Jams    2020-01-09  10
Jams    2020-01-10  1
Jams    2020-01-11  0
Jams    2020-01-12  4
Jams    2020-01-13  5
Candy   2020-01-14  3
Candy   2020-01-15  2
Candy   2020-01-16  0
Candy   2020-01-17  1
Candy   2020-01-18  0
Candy   2020-01-19  1
Candy   2020-01-20  1
Candy   2020-01-21  1
Candy   2020-01-22  4
Candy   2020-01-23  2

从我的数据集中,我需要以下输出:

Product  Count of Consecutive 10's
Jam         5 
Candy       0

我已阅读SybaseIQ帮助指南并尝试使用ROW_NUMBER() OVER ([PARTITION BY window partition] ORDER BY window ordering)分析功能,但我不断收到语法错误。我认为问题在于我无法理解这个计算背后的概念。

如果有人可以帮助我,我将不胜感激。

标签: sqlsap-iq

解决方案


您可以使用窗口函数。对于每个产品,您可以通过计算该行之前的非 10 数来识别相邻匹配行的组。这标识了组。

select name, sum(case when sale = 10 then 1 else 0 end0 as cnt
from (select t.*,
             sum(case when sale <> 10 then 1 else 0 end) over (partition by product order by date) as grp
      from t
     ) t
group by name,
      (case when sale <> 10 then 1 else 0 end),
      grp;

这将返回所有组的值。我想你可能想要最长的,这将是:

select name, max(cnt)
from (select name, sum(case when sale = 10 then 1 else 0 end0 as cnt
      from (select t.*,
                   sum(case when sale <> 10 then 1 else 0 end)
                       over (partition by product
                             order by date
                             rows between unbounded preceding and current row
                            ) as grp
            from t
           ) t
      group by name,
               (case when sale <> 10 then 1 else 0 end),
               grp
     ) t
group by name;

推荐阅读