Partition over a sliding date window

From: Guillaume Roger <guillaume(dot)roger(at)spilgames(dot)com>
To: <pgsql-sql(at)postgresql(dot)org>
Subject: Partition over a sliding date window
Date: 2011-09-13 11:25:39
Message-ID: 4E6F3DB3.4030905@spilgames.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi,

I have a simple table with 3 fields: date, value and username, which can
hold identical rows.

What I am trying to do is to have for each date the count of distinct
username for the 30 previous days.

I was hoping to get this with a partition, as in the following
non-working exemple

SELECT
t.date
, t.value
, COUNT(DISTINCT t.username) OVER (PARTITION date BETWEEN t.date -
INTERVAL '29 days' and t.date)
FROM
table t
GROUP BY
date
, value
, username
;

There are many issues with this query:
- distinct not implemented for window function
- COUNT () OVER is not seen as an aggregate function, I thus need to add
username in the GROUP BY clause, which leads to wrong result
- I am not convinced that the date BETWEEN is valid either, but the
other issues prevent me to check this.

Is there a way to do what I am looking for with partitions, or should I
just give up and use 'usual' sql?

Thanks,
Guillaume

Browse pgsql-sql by date

  From Date Subject
Next Message Dianna Harter 2011-09-13 18:04:34 Window function sort order help
Previous Message Samuel Gendler 2011-09-13 06:45:11 Re: Use select and update together