Вы можете попытаться использовать команду make number в подзапросе, а затем использовать условную агрегатную функцию для ее создания.
CREATE TABLE T(
user_id int,
sent_at timestamp,
campaign_name varchar(50)
);
INSERT INTO T VALUES (101, '2018-10-01 13:04','Google_Branded');
INSERT INTO T VALUES (101, '2018-10-01 13:07','Google_Branded');
INSERT INTO T VALUES (101, '2018-10-02 13:09','Facebook_Focus');
INSERT INTO T VALUES (102, '2018-09-25 13:04','Google_Focus');
INSERT INTO T VALUES (102, '2018-09-27 09:24','Google_Branded');
INSERT INTO T VALUES (102, '2018-10-01 11:25','Google_Branded');
INSERT INTO T VALUES (103, '2018-09-27 13:04','Google_Branded');
INSERT INTO T VALUES (103, '2018-09-28 09:15','Google_Branded');
INSERT INTO T VALUES (103, '2018-09-29 18:34','Google_Branded');
INSERT INTO T VALUES (103, '2018-09-30 21:02','Google_Branded');
Запрос 1 :
SELECT user_id,
MAX(CASE WHEN rn = 1 then campaign_name end) last_click_attribution,
MAX(CASE WHEN rn = 2 then campaign_name end) second_last_ad,
MAX(CASE WHEN rn = 3 then campaign_name end) third_last_ad,
MAX(CASE WHEN rn = 4 then campaign_name end) fourth_last_ad
FROM (
select *,row_number() over(partition by user_id ORDER by sent_at desc) rn
from T
) t1
group by user_id
Результаты :
| user_id | last_click_attribution | second_last_ad | third_last_ad | fourth_last_ad |
|---------|------------------------|----------------|----------------|----------------|
| 101 | Facebook_Focus | Google_Branded | Google_Branded | (null) |
| 102 | Google_Branded | Google_Branded | Google_Focus | (null) |
| 103 | Google_Branded | Google_Branded | Google_Branded | Google_Branded |