【问题标题】:Oracle Select counts/ values from rows into columnsOracle 从行到列中选择计数/值
【发布时间】:2015-07-07 06:24:58
【问题描述】:

我一直在尝试从行中获取一些结果以呈现到列中。

桌子就像,

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,以便它返回所需的结果,或者有更好的方法来实现相同的结果。

在此先感谢

【问题讨论】:

    标签: oracle join count


    【解决方案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
    

    SQLFiddle

    【讨论】:

    • 我的机器上有 Oracle 11g Express Edition,但是您为 Oracle 11 版本共享的查询确实给出了预期的结果,但是第二个完全符合我的要求,您能分享如何更新获得相同结果的第一个查询
    • 感谢您的努力,它现在确实有效,并感谢您展示了改进我的查询的替代和更好的方法:)
    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2022-11-25
    • 2015-07-22
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多