Parul Singh February 2016

Writing rule in Drools - conditional sum

I am stuck in writing a rule for a particular problem statement. I have an excel file having columns id, specialty,salary. Specialty can take values such as "oncology","urology" etc. I have to calculate total salary corresponding to each specialty. There are two ways of doing this.

First:

rule "Total salary of Oncology" 

no-loop
lock-on-active
salience 100
    when

    $m : Masterclass( $id : phyid , $p : p,spec=="Oncology")
     not Masterclass( spec=="Oncology", phyid < $id)
    $total : Number() from accumulate ( Masterclass(  $salary : salary ,spec=="Oncology") ,
                init( double total =0;), 
                action(total+=$salary;),
                result(  new Double (total)))
    then
    System.out.println($m.getSpec());
    System.out.println("Total target pay is : " + $total + " of specialty : "+ $m.getSpec());
    retract($m);
end 

And similarly for other specialties. This rule works fine.

Second: Write only a single rule which reads the value of specialty and then sums up the salaries corresponding to it. I tried to implement this but didn't succeed. Any help will be appreciated.

Answers


laune February 2016

This is far from perfect. But note that you don't have to insert some specific string. Running the rule without a string to match will produce the accumulated sums for all specialities anyway.

And you should wrap the String into a Java class - I was just too lazy to invent a proper Java class with one field.

rule "trigger read"
when
  not String()
then
  String s = read_any_way_you_want();
  insert( s );
end;

rule "Total salary of something" 
when
  $spec: String()
  $m : Masterclass( $id: phyid , spec == $spec)
  not Masterclass( spec == $spec, phyid < $id)
  $total : Number() from
     accumulate ( Masterclass($salary: salary, spec == $spec) ,
            init( double total =0;), 
            action(total+=$salary;),
            result( new Double (total)))
then
  System.out.println($m.getSpec());
  System.out.println("Total target pay is : " + $total + 
                     " o specialty : "+ $m.getSpec());
  retract($spec);
end 

Post Status

Asked in February 2016
Viewed 3,893 times
Voted 9
Answered 1 times

Search




Leave an answer