我正在使用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)分析函数,但我一直收到语法错误。我认为问题是我不能理解这个计算背后的概念。
如果有人能帮助我,我将不胜感激。
发布于 2020-01-16 21:05:18
您可以使用窗口函数。对于每个产品,您可以通过计算该行之前的非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;https://stackoverflow.com/questions/59762887
复制相似问题