我一直试图将行中的一些结果显示在列中。
表就像,
Event_ID
User ID
Event_Type (Call,App)
...
用户可以拥有多个类型的事件,呼叫或约会。我想将结果列为
User_ID Calls_Count Appointments_Count
01 4 10
02 0 12
我已设法编写查询以获得所需结果,但如果用户没有呼叫或约会,则记录不会显示在结果中。
select
distinct(e.user_id),
Call.cc as Call_Count,
App.ac as App_Count
from events e,
(select user_id,event_type,count(user_id) as cc from events c where event_type = 'Call' group by user_id,event_type) Call,
(select user_id,event_type,count(user_id) as ac from events a where event_type = 'App' group by user_id,event_type) App
where e.user_id = Call.user_id
and e.user_id = App.user_id
order by user_id asc
;
如何将此查询转换为使用join
,以便返回所需的结果,或者是否有更好的方法来实现相同的结果。
非常感谢提前
答案 0 :(得分:1)
Oracle 11版本:
select * from events
pivot (count(1) for (event_type) in ('App' Apps, 'Call' Calls))
order by user_id
旧版本:
select user_id,
count(case when event_type = 'App' then 1 end) Apps,
count(case when event_type = 'Call' then 1 end) Calls
from events
group by user_id
order by user_id
修改:对于pivot
的解决方案,最好将列限制为最初让我们感兴趣的列,例如:
select * from (select user_id, event_type from events)
pivot (count(1) for (event_type) in ('App' Apps, 'Call' Calls))
order by user_id