首页 > 解决方案 > 如何创建一个仅计算 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() 函数不会得到这个“累积”信息。所以我有点迷失在这里。

标签: sqlcountamazon-redshiftwindow-functionslag

解决方案


这看起来像前面行的非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

推荐阅读