【问题标题】:How pivot a sum of values如何旋转一个值的总和
【发布时间】:2021-01-21 01:52:36
【问题描述】:

我有一个问题,我怎样才能将聚合结果转为看起来像..

我正在尝试首先使用此查询来转换一个简单的聚合:

select sync_action action, count(sync_action) total
FROM my_table
group by sync_action

并旋转我正在使用的表格:

select * from (  
    select sync_action , count(sync_action) total
    FROM my_table
    group by sync_action  )  
    pivot
    (    
    count(sync_action)
    for sync_action in ('delete','create') 
    )
;

我不知道错误在哪里,因为结果是:

想法与第一张图片相同。

有人可以帮帮我吗?

最好的问候

【问题讨论】:

    标签: sql oracle pivot oracle19c


    【解决方案1】:

    我只会使用条件聚合:

    select 
        sum(case when sync_action = 'delete' then total else 0 end) sum_delete,
        sum(case when sync_action = 'create' then total else 0 end) sum_create
    from mytable
    where sync_action in ('delete', 'create')
    

    【讨论】:

      【解决方案2】:

      你不需要group by,只要喜欢就行了

      SELECT *
      FROM mytable
      pivot 
      ( COUNT(sync_action) 
        FOR sync_action IN('delete','create')
      );
      

      【讨论】:

        【解决方案3】:

        在您的查询中,您需要在数据透视部分中使用“SUM of total”而不是“Count of sync_action”。其他都还好。如果您使用计数,在您的情况下,您将始终得到 1。

        select * from (  
            select sync_action , count(sync_action) total
            FROM my_table
            group by sync_action  ) as p
            pivot
            (    
            sum(p.total)
            for p.sync_action in ("delete","create") 
            )pt
        

        【讨论】:

          【解决方案4】:

          我想你只是想要:

          select sum(case when sync_action = 'delete' then 1 else 0 end) as delete,
                 sum(case when sync_action = 'create' then 1 else 0 end) as create
          from my_table;
          

          我完全看不出pivot 对你想做的事情有什么帮助。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多