ORACLE中多列的总和

时间:2013-02-07 10:38:59

标签: oracle

我有一个包含97列的表,我想总计96列。

select sum(col1+col2+col3+.....+col96) 
from tableA where meter_id=x;

我不想提供所有96个列名,最好的方法是什么? 问候, RR

7 个答案:

答案 0 :(得分:6)

无法避免编写每个列名。你所能做的只是诅咒愚蠢的数据建模器,并忙于切割粘贴。

答案 1 :(得分:4)

在有大量列的情况下,我会看一下使用数据字典表来帮助创建查询,使用如下所示的查询:

Select column_name || '+' as column_name_list
From user_tab_columns
Where table_name = 'TABLEA'
Order by column_id

它不会改变世界,但会简化编写一个查询。

答案 2 :(得分:1)

您可以创建一个virtual column来添加96列,例如:

alter table TABLEA add (MY_TOTAL_COL NUMBER GENERATED ALWAYS AS (col1+col2+col3...) VIRTUAL);

然后您的查询就可以sum(my_total_col)

答案 3 :(得分:1)

您最好对列进行求和,然后将结果放入Excel中以求和之和。否则,此查询应该满足您的需求:

SELECT SUM(TOTAL_SUM) FROM (
  SELECT SUM(column1) AS TOTAL_SUM FROM your_table
  UNION
  SELECT SUM(column2) AS TOTAL_SUM FROM your_table
  UNION
  SELECT SUM(column3) AS TOTAL_SUM FROM your_table
);

答案 4 :(得分:0)

SELECT A.consol_key, 
       A.amt_lcy, 
       B.amt_lcy, 
       C.amt_lcy 
FROM   categ A, 
       spec B, 
       stmt C; 

SELECT Sum(total_sum) 
FROM   (SELECT Sum(amt_lcy) AS TOTAL_SUM 
        FROM   categ 
        UNION 
        SELECT Sum(amt_lcy) AS TOTAL_SUM 
        FROM   spec 
        UNION 
        SELECT Sum(amt_lcy) AS TOTAL_SUM 
        FROM   stmt) 
WHERE  table_id NOT IN (SELECT table_id 
                        FROM   categ 
                        WHERE  txn_code = 'COR' 
                               AND system_id <> 'AA'); 

答案 5 :(得分:0)

有可能:

使用Can an SQL procedure return a table? 以及Mike Meyers的答案,您可以使用动态sql编写存储过程

 sumcolumns(columnfilter,tablename,whereclause)

并使用类似的东西

select * 
  from table(sumcolumns('column_name <> ''col97''','tableA','meter_id=x'))

答案 6 :(得分:0)

尝试按以下示例使用UNPIVOT(仍然需要指定其他人已经指出的列列表):

with tableA as /* prototype tableA just for example */
(
select 1 meter_id, 101 col1, 10 col2, 20 col3, 30 col4, NULL col5, 101 col11, 10 col12, 20 col13, 30 col14, NULL col15, 101 col21, 10 col22, 20 col23, 30 col24, NULL col25  from dual union
select 2, 102, 40, NULL, 50, NULL, 102, 40, NULL, 50, NULL, 102, 40, NULL, 50, NULL  from dual union
select 3, 103, 60, 70, 80, 90, 103, 60, 70, 80, 90, 103, 60, 70, 80, 90  from dual union
select 4, 104, 100, NULL, NULL, NULL, 104, 100, NULL, NULL, NULL, 104, 100, NULL, NULL, NULL  from dual
)
, unpivoted_tableA as /* UNPIVOT tableA columns into rows */
(
select *
from tableA
unpivot include nulls 
(
col_value for col_ in 
 (COL1,COL2,COL3,COL4,COL5,COL11,COL12,COL13,COL14,COL15,COL21,COL22,COL23,COL24,COL25)
)
)
/* main query - Sum of all columns that were unpivoted to rows */
select meter_id, sum(col_value) 
from unpivoted_tableA
group by meter_id
;