sql - 计算产品连续销售的总次数 - 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)
分析功能,但我不断收到语法错误。我认为问题在于我无法理解这个计算背后的概念。
如果有人可以帮助我,我将不胜感激。
解决方案
您可以使用窗口函数。对于每个产品,您可以通过计算该行之前的非 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;
推荐阅读
- python - Tkinter get() 无法返回用户输入
- windows - 为什么 WriteConsoleW 在使用 ml64 调用 CoInitialize 后会中断
- c# - OpenApi 生成的 c# 代码中的不明确引用错误
- php - 动态文件介绍 SQL 查询
- javascript - 使用文件类型的缓冲区中的文件类型
- java - Android Room Java Inner Join with Count
- sql - SQL中的XML PATH是否有替代方案
- android - android studio 无法识别设备上当前安装的 apk(is)
- android - 如何在 Firebase 聊天应用中实现消息可见功能
- python - 如何仅从 excel 文件中过滤出那些具有我在代码中提到的特定单词的评论?