sql - 如何创建一个仅计算 redshift 上其他列变化的列?
问题描述
我有这个数据集:
product customer date value buyer_position
A 123455 2020-01-01 00:01:01 100 1
A 123456 2020-01-02 00:02:01 100 2
A 523455 2020-01-02 00:02:05 100 NULL
A 323455 2020-01-03 00:02:07 100 NULL
A 423455 2020-01-03 00:09:01 100 3
B 100455 2020-01-01 00:03:01 100 1
B 999445 2020-01-01 00:04:01 100 NULL
B 122225 2020-01-01 00:04:05 100 2
B 993848 2020-01-01 10:04:05 100 3
B 133225 2020-01-01 11:04:05 100 NULL
B 144225 2020-01-01 12:04:05 100 4
数据集包含公司销售的产品和看到产品的客户。一个客户可以看到多个产品,但是产品+客户的组合没有任何重复。我想在客户看到产品之前了解有多少人购买了该产品。
这将是完美的输出:
product customer date value buyer_position people_before
A 123455 2020-01-01 00:01:01 100 1 0
A 123456 2020-01-02 00:02:01 100 2 1
A 523455 2020-01-02 00:02:05 100 NULL 2
A 323455 2020-01-03 00:02:07 100 NULL 2
A 423455 2020-01-03 00:09:01 100 3 2
B 100455 2020-01-01 00:03:01 100 1 0
B 999445 2020-01-01 00:04:01 100 NULL 1
B 122225 2020-01-01 00:04:05 100 2 1
B 993848 2020-01-01 10:04:05 100 3 2
B 133225 2020-01-01 11:04:05 100 NULL 3
B 144225 2020-01-01 12:04:05 100 4 3
可以看到,当客户 122225 看到他想要的产品时,已经有两个人购买了。在客户 323455 的情况下,有两个人已经购买了产品 A。
我想我应该使用一些窗口函数,比如 lag()。但是 lag() 函数不会得到这个“累积”信息。所以我有点迷失在这里。
解决方案
这看起来像前面行的非null
值的窗口计数:buyer_position
select t.*,
coalesce(count(buyer_position) over(
partition by product
order by date
rows between unbounded preceding and 1 preceding
), 0) as people_before
from mytable t
推荐阅读
- sap - SAP Cloud SDK JS 从 Enterprise Messaging Queue 接收空数据
- highcharts - 从最小值开始 x 轴
- react-native - 当位置为绝对时,onPress 事件在动画视图中不起作用
- autodesk-forge - Autodesk Forge 中的 BIM 360 扩展
- python - 加载标签以在 Python 中对组织病理学图像进行分类
- micronaut - 将 micronaut 项目转换为 micronaut servlet 后出现运行时错误
- mysql - MySQL 截断双精度值
- typescript - 具有作为参数传递的函数参数的泛型函数
- automation - 基于偶数的任务的深度安全 API 调用
- aws-lambda - 索引处理程序未定义或未导出