透视事件流表(sql)

问题描述 投票:0回答:1

我目前有一张看起来像这样的表:

account_id | order_id | activity_name | activity_date | asc_nbr | desc_nbr
123 | 55 | clicked_page | Sept 15, 2019 | 1 | 4
123 | 55 | clicked_page | Sept 16, 2019 | 2 | 3
123 | 55 | clicked_page | Sept 17, 2019 | 3 | 2
123 | 55 | clicked_page | Sept 18, 2019 | 4 | 1

并且我想将其转换为数据透视表样式,并显示单击的第一个日期和最后一个日期:

account_id | order_id | first_click_date | last_click_date
123 | 55 | Sept 15, 2019 | Sept 18, 2019

但是我的查询以非常奇怪的格式返回数据...查询看起来像:

select account_id
, order_id
, case when activity_name = 'clicked_page' and asc_nbr = 1 then activity_date end as first_click_date
, case when activity_name = 'clicked_page' and desc_nbr = 1 then activity_date end as last_click_date

from table name

^^^以上查询返回的数据集如下所示:

account_id | order_id | first_click_date | last_click_date
123 | 55 | Sept 15, 2019 | null
123 | 55 | null | Sept 18, 2019

我是不是想念一个人吗?

sql events duplicates pivot rank
1个回答
0
投票
with test as (
select '123' as account_id, '55' as order_id, 'clicked_page' as activity_name, 'Sept 15, 2019' as activity_date, 1 as asc_nbr, 4 as desc_nbr
union all  
select '123' as account_id, '55' as order_id, 'clicked_page' as activity_name, 'Sept 16, 2019' as activity_date, 2 as asc_nbr, 3 as desc_nbr  
union all  
select '123' as account_id, '55' as order_id, 'clicked_page' as activity_name, 'Sept 17, 2019' as activity_date, 3 as asc_nbr, 2 as desc_nbr  
union all  
select '123' as account_id, '55' as order_id, 'clicked_page' as activity_name, 'Sept 18, 2019' as activity_date, 4 as asc_nbr, 1 as desc_nbr
)  
select account_id, order_id 
    , min(case when activity_name = 'clicked_page' and asc_nbr = 1 then activity_date end) as first_click_date 
    , max(case when activity_name = 'clicked_page' and desc_nbr = 1 then activity_date end) as last_click_date
from test
group by account_id, order_id
© www.soinside.com 2019 - 2024. All rights reserved.