Count Distinct Over Window Workaround

COUNT(DISTINCT x) OVER fails in PostgreSQL with 'DISTINCT is not implemented for window functions'; deduplicate first, then window-count.

SqlData Fetching

Code

snippet
WITH visits(user_id, page) AS (
    VALUES
        (1, 'home'),
        (1, 'pricing'),
        (1, 'home'),
        (2, 'blog'),
        (2, 'home'),
        (3, 'pricing')
),
-- 直接写 COUNT(DISTINCT page) OVER (PARTITION BY user_id) 会失败:
-- ERROR:  DISTINCT is not implemented for window functions
-- 替代做法:先按列去重,再对去重结果做窗口计数
distinct_pages AS (
    SELECT DISTINCT user_id, page FROM visits
),
pages_per_user AS (
    SELECT user_id, COUNT(*) OVER (PARTITION BY user_id) AS distinct_pages
    FROM distinct_pages
)
SELECT
    v.user_id,
    v.page,
    COUNT(*) OVER (PARTITION BY v.user_id) AS total_visits,
    p.distinct_pages
FROM visits v
JOIN pages_per_user p USING (user_id)
ORDER BY v.user_id, v.page;
-- 另一个等价技巧:DENSE_RANK() OVER (PARTITION BY user_id ORDER BY page)
-- 的最大值就等于该分区的去重个数。

Inside the snippet

What runs is SELECT, with visits, distinct_pages and pages_per_user as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; COUNT aggregation; a window function (OVER (…)) calculating over row windows with no rows folded away; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.

What to watch for

  • To filter on a window function’s result you need an outer query or CTE; the same-level WHERE runs too early.

Using it

Run the statement against the visits table.

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
The references are `visits`, `distinct_pages`, `pages_per_user`, with one join tying the pair together.