繁体   English   中英

透视事件流表 (sql)

[英]Pivoting event streams table (sql)

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

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

我想将其转换为 pivot 表格样式并显示点击的第一个和最后一个日期:

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

我在这里错过了一个小组或其他什么吗?

您只需要条件聚合,聚合 function 是max()还是min()都无关紧要(两者都产生相同的结果):

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 tab
 group by account_id, order_id 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM