简体   繁体   中英

PL/SQL sum values in a column based on another columns value being

I'm trying to display charges only if allowance is zero, and my other my problem is, if I have more than one zero in the allowance column, I only want those charges summed. The one that are not at zero then I do not want to include them in the sum.

Allowa  charges
-----------------------------------------------
84.27   90  0   188428752   2012-05-17 00:00:00
0       100 0   188428752   2013-08-08 00:00:00
84.27   90  0   188428752   2012-06-14 00:00:00
124.7   130 0   188428752   2012-05-10 00:00:00
90.79   90  0   188428752   2012-08-09 00:00:00
90.79   100 0   188428752   2012-10-11 00:00:00
90.79   100 0   188428752   2013-05-23 00:00:00

Charges should be 100

Allowa  charges
-------------------------------------------------
  0       100     188428752   2013-08-08 00:00:00
  0       90      188428752   2012-06-14 00:00:00
  90.79   100 0   188428752   2012-10-11 00:00:00
  90.79   100 0   188428752   2013-05-23 00:00:00

Charges should be 190.

This pl/sql only gives me the total sum.

create or replace procedure summary
as
cursor c1
is
select allowance,sum(charges) CH,sum(not_paid) np ,patientid
from claims1 a, claim_details b
where a.claimid = b.claimid
group by allowance, charges,not_paid,patientid;

ins_bal number(9,2);
pat_bal number(9,2);

begin

for a1 in c1 loop

if a1.allowance = 0 then
ins_bal:=a1.CH;
end if;

if a1.allowance != 0 then
 pat_bal:=a1.np;
end if;

insert into summary_hold values(ins_bal,pat_bal,a1.patientid);
commit;

end loop;
end;
/

 This is the final pl/sql
create or replace procedure summary
as
cursor c1
is
select allowance,(case nvl(allowance,0)  when 0 then sum(charges) else 0 end)CH,
(case when nvl(not_paid,0) <> 0 then sum(not_paid) else 0 end) np,patientid,datefrom
from claims1 a, claim_details b
where a.claimid = b.claimid
group by allowance, charges,not_paid,patientid,datefrom;


begin

for a1 in c1 loop

insert into summary_hold values(a1.ch,a1.np,a1.patientid);
commit;

end loop;
end;
/

Just use CASE statement. sum(case Allowa when 0 then charges else 0 end) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM