示例數據:
create table event_tracking (event_id int, user_id int, event_wave int);
insert into event_tracking values
(123, 10, 3),
(123, 20, 2),
(123, 30, 1);
如果你想獲得所有用戶的事項標識= 123:
select count(*), max(event_wave), array_agg(user_id) users
from event_tracking
where event_id = 123;
count | max | users
-------+-----+------------
3 | 3 | {10,20,30}
(1 row)
如果你想要的事項標識= 123,最大event_wave用戶:
select distinct on (event_id)
row_number() over (order by event_wave) as count,
event_wave as max,
user_id
from event_tracking
where event_id = 123
order by event_id, event_wave desc;
count | max | user_id
-------+-----+---------
3 | 3 | 10
(1 row)
如果你想擁有簡單的是/否對於一個給定的user_id:
select count(*), max(event_wave), 456 = any(array_agg(user_id)) yesno
from event_tracking
where event_id = 123;
或
select distinct on (event_id)
row_number() over (order by event_wave) as count,
event_wave as max,
user_id = 456 yesno
from event_tracking
where event_id = 123
order by event_id, event_wave desc;
的'array_agg'功能做了完美的工作,謝謝指點出來。 – 3kt