【问题标题】:Oracle Sum subtotal QueryOracle Sum 小计查询
【发布时间】:2022-01-24 23:36:40
【问题描述】:

请帮忙 要求是加入小计的总和。

我有一个这样的结果表。 Picture Table

CID     | STORECODE | STORENAME | CONTRACTNO | SUBTOTAL
---------------------------------------------------------
222     | SCI-SCG5  | S2        | 111        | 657,534.20
221     | SCI-SCG5  | S2        | 110        | 700,000

如何得到这样的结果:

CID     | STORECODE | STORENAME | CONTRACTNO | SUBTOTAL
----------------------------------------------------------
222,221 | SCI-SCG5  | S2        | 111,110    | 1.357.534,20

STORECODE | STORENAME | SUBTOTAL
--------------------------------
SCI-SCG5  | S2        | 1.357.534,20

【问题讨论】:

  • 第二个选项是一个简单的聚合。你试过什么?

标签: sql oracle


【解决方案1】:

您可以使用listagg 在 oracle 中聚合组内的字符串:

select listagg(CID,', ') within group( order by CID desc) as CID,
storecode,
storename,
listagg(contractno,', ') within group( order by contractno desc) as CID,
sum(subtotal) as subtotal
from yourtable 
group by storecode, storename;

Fiddle

【讨论】:

    【解决方案2】:

    不同种类的聚合:

    SQL> with test (cid, storecode, storename, contractno, subtotal) as
      2    (select 222, 'SCI-SCG5', 'S2', 111, 657534.20 from dual union all
      3     select 221, 'SCI-SCG5', 'S2', 110, 700000    from dual
      4    )
      5  select
      6    listagg(cid, ',') within group (order by cid) cid,
      7    storecode,
      8    storename,
      9    listagg(contractno, ',') within group (order by contractno) contractno,
     10    sum(subtotal) subtotal
     11  from test
     12  group by storecode, storename;
    
    CID             STORECOD ST CONTRACTNO             SUBTOTAL
    --------------- -------- -- -------------------- ----------
    221,222         SCI-SCG5 S2 110,111               1357534,2
    
    SQL>
    SQL> with test (cid, storecode, storename, contractno, subtotal) as
      2    (select 222, 'SCI-SCG5', 'S2', 111, 657534.20 from dual union all
      3     select 221, 'SCI-SCG5', 'S2', 110, 700000    from dual
      4    )
      5  select storecode, storename, sum(subtotal) subtotal
      6  from test
      7  group by storecode, storename;
    
    STORECOD ST   SUBTOTAL
    -------- -- ----------
    SCI-SCG5 S2  1357534,2
    
    SQL>
    

    【讨论】:

    • 不客气。
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    相关资源
    最近更新 更多