You can do this without OLAP functions but it is messy and performance may be an issue.
I've assumed that you don't really want any null 'missing_sum' values, which your CASE statement would actually return. I've also removed 'agent_id' from the result set for clarity as you already appear to have this in your application(?).
The initial rewrite of your query looks like this...
Code:
select plan_num
, sum(po_amount)
from alliance.po po
where agentid = 5084
and not exists (
select plan_num
from alliance.po po2
where po2.plan_num = po.plan_num
and po2.agent_id = po.agent_id
and po2.po_amount is null
)
group by plan_num
;
If you want to include a grand total, introduce a scalar sub-select in your SELECT statement...
Code:
select po.plan_num
, sum(po_amount)
, (
select sum(po_amount)
from alliance.po po2
where agentid = 5084
and not exists (
select plan_num
from alliance.po po2
where po2.plan_num = po.plan_num
and po2.agent_id = po.agent_id
and po2.po_amount is null
)
)
from alliance.po po
where agentid = 5084
and not exists (
select plan_num
from alliance.po po2
where po2.plan_num = po.plan_num
and po2.agent_id = po.agent_id
and po2.po_amount is null
)
group by po.plan_num
;
If you want to have a running total, self join to all rows where the joining field(s) has a lesser or equal value to the current row's (I've also had to nest the initial SELECT to aggregate the po_amount values) ...
Code:
select po1.plan_num
, po1.po_amount
, sum(po2.po_amount) agg_total
from (
select agent_id
, plan_num
, sum(po_amount) po_amount
from alliance.po po1
where agent_id = 5084
and not exists (
select plan_num
from alliance.po po
where po.plan_num = po1.plan_num
and po.agent_id = po1.agent_id
and po.po_amount is null
)
group by agent_id, plan_num
) po1
, alliance.po po2
where po1.agent_id = po2.agent_id
and exists (
select plan_num
from po1
where po1.plan_num = po2.plan_num
and po1.agent_id = po2.agent_id
)
and po1.plan_num >= po2.plan_num
group by po1.plan_num, po1.po_amount
;
These are all untested because I obviously don't have access to your data.
Damian