Sql 要将不同行中的两个事件合并为一个
我有来自Mixpanel的数据,其中包含两个不同的事件,具有相同的不同的\u id。然后将这些数据提取到列中 数据需要在SQL中进行数据透视,才能在同一行上显示两个事件的输出 数据示例:Sql 要将不同行中的两个事件合并为一个,sql,sql-server,Sql,Sql Server,我有来自Mixpanel的数据,其中包含两个不同的事件,具有相同的不同的\u id。然后将这些数据提取到列中 数据需要在SQL中进行数据透视,才能在同一行上显示两个事件的输出 数据示例: | distinct_id | event | output_event1 | output_event2 | |-------------|-------|---------------|---------------| | 78 | event1| output1 |
| distinct_id | event | output_event1 | output_event2 |
|-------------|-------|---------------|---------------|
| 78 | event1| output1 | NULL |
| 78 | event2| NULL | output2 |
期望输出:
| distinct_id | output_event1 | output_event2 |
|-------------|---------------|---------------|
| 78 | output1 | output2 |
到目前为止,我尝试的查询使用子句尝试了两个,但效率低下,我希望在更多列中显示相同表中的更多信息。此版本查询的另一个限制是,它显示的ID不是event1
的事件输出,而是可通过子查询修复的ID。。。我认为这会进一步降低效率,我正在寻求帮助
with event1 as (
select max(e.id) as id, e.event1, e.distinct_id -- multiple events are possible, select most recent one
from mixpanel.events e where event='event1'
group by event, distinct_id)
, event2 as (
select e.id, e.event, e.distinct_id, e.event2
from mixpanel.events e where event='event2')
select s.distinct_id, s.id, f.id, f.event2
from event1 s
left join event2 f on s.distinct_id=f.distinct_id
提前谢谢 为什么不删除子查询并在主查询中使用聚合
select
distinct_id
,output_event1 = max(output_event1)
,output_event2 = max(output_event2)
from
yourTable
group by
distinct_id
为什么不删除子查询并在主查询中使用聚合
select
distinct_id
,output_event1 = max(output_event1)
,output_event2 = max(output_event2)
from
yourTable
group by
distinct_id
如果您在event
中有其他事件类型,或者由于某种原因无法使用简单的max()
使用条件聚合:
select
distinct_id
, output_event1 = max(case when event='event1' then event1 end)
, output_event2 = max(case when event='event2' then event2 end)
from mixpanel.events
group by distinct_id
如果您在event
中有其他事件类型,或者由于某种原因无法使用简单的max()
使用条件聚合:
select
distinct_id
, output_event1 = max(case when event='event1' then event1 end)
, output_event2 = max(case when event='event2' then event2 end)
from mixpanel.events
group by distinct_id
这看起来是最简单的方法,+1谢谢,我必须在需要分组的列上玩一点,但这很有效。这看起来是最简单的方法,+1谢谢,我必须在需要分组的列上玩一点,但这是可行的。我认为问题不可能列出所有细节:)我认为问题不可能列出所有细节:)