7

我有一个有 97 列的表,我想对 96 列求和。

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

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

4

7 回答 7

9

没有办法避免写入每个列名。您所能做的就是诅咒愚蠢的数据建模师并忙于剪切粘贴。

于 2013-02-07T10:44:26.360 回答
5

在有大量列的情况下,我会考虑使用数据字典表来帮助创建查询,方法是使用如下查询:

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

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

于 2013-02-07T20:05:51.533 回答
1

您可以创建一个虚拟列,将 96 列相加,例如:

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

然后你的查询可以简单地做sum(my_total_col)

于 2013-02-07T17:11:41.057 回答
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
);
于 2017-07-12T12:32:32.037 回答
0

有可能:

使用SQL 过程可以返回表吗? 以及 Mike Meyers 的回答,您可以使用动态 sql 编写存储过程

 sumcolumns(columnfilter,tablename,whereclause)

并使用它

select * 
  from table(sumcolumns('column_name <> ''col97''','tableA','meter_id=x'))
于 2020-03-06T11:40:21.300 回答
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'); 
于 2020-03-06T09:45:03.817 回答
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
;
于 2020-03-06T14:38:12.437 回答