在oracle中使用SUM函数

Use SUM function in oracle

我在 Oracle 中有一个 table,其中包含:

 id | month | payment | rev
----------------------------
  A |  1    |  10     |  0
  A |  2    |  20     |  0
  A |  2    |  30     |  1
  A |  3    |  40     |  0
  A |  4    |  50     |  0
  A |  4    |  60     |  1
  A |  4    |  70     |  2

我要计算付款列(SUM(payment))。对于 (id=A month=2)(id=A month=4),我只想从 REV 列中获取最大值。这样总和就是(10+30+40+70)=150。怎么做?

select sum(payment) from tableName where id='A' and month=2 OR month=4 order by payment asc;

这假定您的每个转数不超过一个值。如果不是这种情况,那么您可能需要 row_number 分析而不是 max.

with latest as (
  select
    id, month, payment, rev,
    max (rev) over (partition by id, month) as max_rev
  from table1
)
select sum (payment)
from latest
where rev = max_rev

您也可以在下方使用。

select id,sum(payment) as value
    from 
    (
    select id,month,max(payment) from table1
    group by id,month
    )
    group by id

Edit: 用于检查最大转速值

select id,sum(payment) as value
from (
select id,month,rev,payment ,row_number() over (partition by id,month order by rev desc) as rno     from table1
) where rno=1
group by id

或者有这个,如果我理解正确的话:

with demo as (
    select 'A'as id, 1 as month, 10 as payment, 0 as rev from dual
    union all select 'A',2,20,0 from dual
    union all select 'A',2,30,1 from dual
    union all select 'A',3,40,0 from dual
    union all select 'A',4,50,0 from dual
    union all select 'A',4,60,1 from dual
    union all select 'A',4,70,2 from dual
)
select sum(payment) keep (dense_rank last order by rev)
from   demo;

您可以通过包含关键列来检查细分:

with demo as (
    select 'A'as id, 1 as month, 10 as payment, 0 as rev from dual
    union all select 'A',2,20,0 from dual
    union all select 'A',2,30,1 from dual
    union all select 'A',3,40,0 from dual
    union all select 'A',4,50,0 from dual
    union all select 'A',4,60,1 from dual
    union all select 'A',4,70,2 from dual
)
select id, month, max(rev)
     , sum(payment) keep (dense_rank last order by rev)
from   demo
group by id, month;