如何在Oracle数据透视表中包含行合计?

unguejic  于 2023-05-06  发布在  Oracle
关注(0)|答案(5)|浏览(154)

我有一个数据表,请参阅使用透视表语句,我可以按标题分解计数

select * from (
  select * from ta
)
pivot (
COUNT(title)
 for title in ( 'worker', 'manager') )

结果是这样的:

STATUS    'worker'  'manager'
started   3         1
finished  4         5
ready     3         4

我需要为行总计添加第三列

STATUS    'worker'  'manager'  Total
started   3         1          4
finished  4         5          9
ready     3         4          7

你知道我如何在同一个声明中实现这一点吗?演示位于http://sqlfiddle.com/#!4/740fd/1

kpbpu008

kpbpu0081#

我只会使用条件聚合而不是pivot。这为您提供了所需的额外灵活性:

select 
    status,
    sum(case when title = 'worker'  then 1 else 0 end) worker,
    sum(case when title = 'manager' then 1 else 0 end) manager,
    count(*) total
from ta
group by status

Demo on DB Fiddle

STATUS   | WORKER | MANAGER | TOTAL
:------- | -----: | ------: | ----:
started  |      3 |       1 |     4
finished |      4 |       5 |     9
ready    |      3 |       4 |     7
vyswwuz2

vyswwuz22#

使用SUM()分析函数获得总数,然后使用PIVOT

select 
    status,
    sum(case 
        when title = 'worker' 
          then 1 
            else 0
        end) worker,
    sum(case
        when title = 'manager' 
          then 1 
            else 0 
        end) manager,
    count(*) total
from ta
group by status

tzxcd3kk

tzxcd3kk3#

为整个查询给予一个别名(例如q),以便用星号(q.*)限定所有列,然后将所有列相加,以产生total列:

select q.*, worker + manager as total 
  from ta
 pivot 
 (
  count(title)
  for title in ( 'worker' as worker, 'manager' as manager ) 
 ) q

Demo

moiiocjp

moiiocjp4#

我认为其他的例子要简单得多,但这里是一个在旋转之前使用cubegrouping的不同方法:

select *
from (
select decode(grouping(title),1,'total',0,title) title,
       status,
       count(*) cnt
from ta
group by status, cube(title) )
pivot(
  sum(cnt) for title in ('worker','manager','total')
)

输出:

|   STATUS | 'worker' | 'manager' | 'total' |
|----------|----------|-----------|---------|
| finished |        4 |         5 |       9 |
|    ready |        3 |         4 |       7 |
|  started |        3 |         1 |       4 |

http://sqlfiddle.com/#!4/740fd/13/0
cube添加到group by子句中将给予该列的小计。默认情况下,它将在该列中显示为null。您可以在select子句中使用grouping函数来区分总计行和普通行(总计行为1,普通行为0)。使用解码将强制这些总行为'total',这将成为您可以透视的值之一。

sr4lhrrt

sr4lhrrt5#

这将为访问此页面的任何人解决您的问题:

SELECT PVT.*, (COALESCE(PVT."worker",0) + COALESCE(PVT."manager",0)) AS "TOTAL"
FROM
(
select * from (
  select * from ta
)
pivot (
COUNT(title)
 for title in ( 'worker' AS "worker", 'manager' AS "manager") )
)PVT

备注:
1.您可以使用额外的外部查询来解决此问题
1.通过对Pivot子句中的列使用别名,可以轻松地调用外部查询中的列
1.在外部查询中使用coalesce可为manager和worker列返回0而不是null。这确保了即使worker或manager列具有空值,total列也总是有要添加的内容。

相关问题