oracle 如何对一列求和,然后按求和后的列分组

o2gm4chl  于 2023-05-16  发布在  Oracle
关注(0)|答案(3)|浏览(178)

我有一个表,其中包含以下内容

Col A          
10
20
30

我想要这个结果

Col A         Col B
10             60
20             60
30             60
ygya80vv

ygya80vv1#

在其分析版本中使用sum

SQL> with test (cola) as
  2    (select 10 from dual union all
  3     select 20 from dual union all
  4     select 30 from dual
  5    )
  6  select cola,
  7    sum(cola) over () colb        --> this
  8  from test;

      COLA       COLB
---------- ----------
        10         60
        20         60
        30         60

SQL>
nue99wik

nue99wik2#

只要在解析函数上求和,你就会得到想要的结果.

select colA,sum(colA) over() colB from Table;
igsr9ssn

igsr9ssn3#

使用您的示例数据:

WITH tbl (COL_1) AS
(   
    SELECT 10 FROM Dual UNION ALL
    SELECT 20 FROM Dual UNION ALL
    SELECT 30 FROM Dual
)

...您可以选择总和作为子查询列:

Select    COL_1, ( Select Sum(COL_1) From tbl ) "COL_2"
From      tbl 
Order By  COL_1

…或者可以使用sum子查询连接表

Select  t1.COL_1, t2.COL_2
From    tbl t1
Inner Join (Select Sum(COL_1) "COL_2" From tbl  ) t2 ON(1 = 1)
Order By t1.COL_1

两者都得到:

COL_1      COL_2
---------- ----------
        10         60
        20         60
        30         60

相关问题