postgresql 计算累积非重复

hrysbysz  于 2023-03-01  发布在  PostgreSQL
关注(0)|答案(2)|浏览(124)

我在数据库中有一个表,其中包含:

  • 创建时间
  • 订单标识
  • 客户标识

我想计算每天的累计非重复客户数。
我写了这个查询

SELECT
    created_at::date,
    COUNT(DISTINCT customer_id) OVER (ORDER BY created_at::date) as cumulative_users
FROM orders
GROUP BY 1
ORDER BY 1

然后我发现PostgreSQL在窗口函数中不支持distinct。
你能帮我写这段代码吗?

ukxgm1gy

ukxgm1gy1#

没有窗口功能需要在这里imho。

select created_at , count(distinct customer_id) from order_table group by created_at;

请参阅SQLFiddle

kcwpcxri

kcwpcxri2#

WITH firstseen AS (
    SELECT
        customer_id,
        MIN(created_at) created_at
    FROM orders
    GROUP BY 1
)
SELECT
    DISTINCT created_at :: date,
    COUNT(customer_id) OVER (ORDER BY created_at :: date) daily_cumulative_count
FROM firstseen
ORDER BY 1

相关问题