我有一个看起来像这样的表(在 Postgres 9.1 中):
CREATE TABLE actions (
user_id: INTEGER,
date: DATE,
action: VARCHAR(255),
count: INTEGER
)
例如:
user_id | date | action | count
---------------+------------+--------------+-------
1 | 2013-01-01 | Email | 1
1 | 2013-01-02 | Call | 3
1 | 2013-01-03 | Email | 3
1 | 2013-01-04 | Call | 2
1 | 2013-01-04 | Voicemail | 2
1 | 2013-01-04 | Email | 2
2 | 2013-01-04 | Email | 2
我希望能够查看用户在一段时间内针对一组特定操作的总操作;例如,电话 + 电子邮件:
user_id | date | count
-----------+-------------+---------
1 | 2013-01-01 | 1
1 | 2013-01-02 | 4
1 | 2013-01-03 | 7
1 | 2013-01-04 | 11
2 | 2013-01-04 | 2
到目前为止,我创建的怪物看起来像这样:
SELECT
date, user_id, SUM(count) OVER (PARTITION BY user_id ORDER BY date) AS count
FROM
actions
WHERE
action IN ('Call', 'Email')
GROUP BY
user_id, date, count;
这适用于单个动作,但似乎在同一天发生多个动作时会中断,例如,而不是预期的11
on 2013-01-04
,我们得到9
:
date | user_id | count
------------+--------------+-------
2013-01-01 | 1 | 1
2013-01-02 | 1 | 4
2013-01-03 | 1 | 7
2013-01-04 | 1 | 9 <-- should be 11?
2013-01-04 | 2 | 2
是否可以调整我的查询以解决此问题?我尝试在 上删除分组count
,但 Postgres 似乎不喜欢这样:
column "actions.count" must appear in the GROUP BY clause or be used in an aggregate function LINE 2: date, user_id, SUM(count) OVER (PARTITION BY user... ^