如何旋转值的总和

How pivot a sum of values

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

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

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

并旋转 table 我正在使用:

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') 
    )
;

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

思路和第一张图一样。

有人可以帮助我吗?

此致

我只想使用条件聚合:

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')

你不需要做group by,只是喜欢

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

在您的查询中,数据透视部分需要“总和”而不是“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

我想你只是想要:

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 对您想做的事情有什么帮助。