如何支配价值总和

问题描述

我有一个问题,如何将汇总结果显示为..

enter image description here

我正在尝试首先使用此查询来进行简单的汇总:

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

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

enter image description here

这个主意与第一张图片相同。

有人可以帮我吗?

最诚挚的问候

解决方法

我只会使用条件聚合:

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的计数”。其他的还可以。如果您使用count,那么在您的情况下,您将始终获得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对您想做什么的帮助。