例如,我有一张桌子
date id event
1999-01-01 1 buy
1999-01-05 2 return
1999-01-10 3 buy
1999-02-01 1 return
1999-02-01 4 buy
1999-02-01 5 return
我需要创建一个看起来像这样的表:
month count_buy count_return_from_last_month
1999-01 2 ? (or none, we don't have data on this, no need to specify)
1999-02 1 1
第三列计算上个月购买的ID并返回当月的ID
我想这可以通过交叉表解决,但我找不到找到第三列条件的方法
谢谢!
这应该做:
WITH counts AS (
SELECT
to_char(date, 'YYYY-MM') AS month,
count(*) filter (WHERE event = 'buy') AS count_buy,
count(*) filter (WHERE event = 'return') AS count_return
FROM data
GROUP BY 1
)
SELECT
month,
count_buy,
lag(count_return) OVER (ORDER BY month) AS count_return_from_last_month
FROM counts
ORDER BY month;
尽管请注意,要使lag
始终为上个月,您需要对每个月进行计数。如果数据中有漏洞,则滞后将选择上一个可用月份。