2016-07-12 115 views
0

我有一個事件跟蹤表,它將事件鏈接到受這些事件影響的用戶。對於特定的event_id對應幾個user_id。每個event_tracking元素還有一個event_wave號碼。在子查詢結果中查找特定值

對於某個特定事件,我希望提取受其影響的用戶數量,最大事件波形(1)以及用戶是否受到事件影響(2) 。

SELECT COUNT(*), MAX(event_wave) 
FROM event_tracking 
WHERE event_id = 123 

和(2)使用:

另外我可以(1)使用做

SELECT 456 = ANY(SELECT user_id FROM event_tracking WHERE event_id = 123) 

然而,是有可能有那些結果(1 & 2),而不使用2-子查詢?

回答

2

示例數據:

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; 
+0

的'array_agg'功能做了完美的工作,謝謝指點出來。 – 3kt

0

嘗試

SELECT COUNT(*), MAX(event_wave), 
     MIN(CASE WHEN user_id = 459 THEN 'yes' END) 
      As user_459_impacted 
FROM event_tracking 
WHERE event_id = 123