我使用的是 Postgres 9.4,我有一个如下所示的查询:
SELECT attendees.event_id, attendees.user_id, users.tags
FROM users, attendees
WHERE 'crystal:promo' = ANY(users.tags)
AND users.id = attendees.user_id
AND attendees.status = 'paid'
GROUP BY attendees.event_id, attendees.user_id, users.tags
ORDER BY attendees.event_id desc;
结果:
event_id | user_id | tags
----------+---------+------
1 | 2 | ...
1 | 4 | ...
1 | 7 | ...
我想为每一行添加一个摘要列,该列是每个事件的总人数,与用户标签无关,这样结果将类似于:
select count(*) from attendees where status='paid' group by event_id
并加入上述结果(假设 11 支付):
event_id | user_id | tags | total_event_paid
----------+---------+------+------------------
1 | 2 | ... | 11
1 | 4 | ... | 11
1 | 7 | ... | 11
您可以只替换
attendees
为预先选择“付费”行的子查询,并在不聚合的情况下添加计数 - 使用窗口函数:DISTINCT
(orGROUP BY
) 在外部SELECT
可能需要也可能不需要。有关的:
从9.4开始,您可以将窗口函数与
FILTER
. 就像是: