简体   繁体   English

在 Oracle 中为多列计算和添加总计行

[英]Calculating and adding the totals row in Oracle for multiple columns

I am new to sql and oracle.我是 sql 和 oracle 的新手。 Below is the result of a complicated and time consuming query.下面是一个复杂且耗时的查询的结果。 I would like to calculate the sums for col2, col3 and col4.我想计算 col2、col3 和 col4 的总和。 I would like to add a totals row at the end of the table.我想在表的末尾添加一个总计行。

Current Output.电流输出。

id  rate rate2 col2      col3  col4
1   2,3  11    10        36     10      
1   2,4  2     229,32    36     229,32      
1   3    44    229,32    36     229,32      
1   4,5  3,4   165,2     36     90,2    
81  1,1  11    30,3      36     30,3        
81  2,3  22    10        36     10      

Desired Result.想要的结果。 (N stands for null) (N 代表空)

id  rate rate2 col2      col3  col4
1   2,3  11    10        36     10      
1   2,4  2     229,32    36     229,32      
1   3    44    229,32    36     229,32      
1   4,5  3,4   165,2     36     90,2    
81  1,1  11    30,3      36     30,3        
81  2,3  22    10        36     10  
N   N    N     674,14    216    599,14  

I have been doing some searching, i am able to manage this using UNION .我一直在做一些搜索,我能够使用UNION来管理它。 However there is performance issue, i am running the same query calculating the totals and appending.但是存在性能问题,我正在运行相同的查询来计算总数和附加。 Bottom line is i don`t want to run the same time consuming query twice.底线是我不想两次运行相同的耗时查询。 Is there any other way to manage this ?有没有其他方法来管理这个?

Thanks in advance.提前致谢。

Probably the simplest method is to use union all :可能最简单的方法是使用union all

with q as (
      <your query here>
     )
select q.*
from q
union all
select null, null, null, sum(col2), sum(col3), sum(col4)
from q;

Because Oracle sometimes materializes CTEs, there is not necessarily much impact on performance.由于 Oracle 有时会实现 CTE,因此不一定会对性能产生太大影响。

If your complicated query is an aggregation that ends in:如果您的复杂查询是以以下结尾的聚合:

group by id, rate, rate2

Then grouping sets is another option:然后grouping sets是另一种选择:

group by grouping sets ( (id, rate, rate2), () )

You can use CTE and MATERIALIZE hint to fetch the desired output as following:您可以使用CTEMATERIALIZE提示来获取所需的输出,如下所示:

with cte as (SELECT /*MATERIALIZE*/ <your query after select>)
select c.*
  from cte c
union all
select null, null, null, sum(col2), sum(col3), sum(col4)
  from cte;

The undocumented MATERIALIZE hint uses global temporary table so there will be no or little performance impact.未记录的MATERIALIZE提示使用全局temporary table因此不会或几乎没有性能影响。

Cheers!!干杯!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM