Oracle Select 从行到列的计数/值

Oracle Select counts/ values from rows into columns

我一直在尝试从行中获取一些结果以显示在列中。

Table 就像,

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,以便 returns 获得所需的结果,或者是否有更好的方法来实现相同的结果。

非常感谢

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

SQLFiddle