trying to create a trigger on supabase to calculate a winrate based on two other columns
hi all, tsuki here. i'm trying to create a trigger that fires before updates, that should calculate a win percentage based on my
wins
wins
column and my
losses
losses
column.
the trigger is firing correctly, but it seems like it isn't correctly calculating the win percentage?
i expected the attached image to have
winrate
winrate
as
60.00
60.00
or
60
60
given the calculation of
6 / (6 + 4) * 100
6 / (6 + 4) * 100
.
the code used to create the trigger in the sql editor on supabase some of which was written by the supabase ai helper.
createor replace function calculate_winrate () returns trigger as $$begin new.winrate = (new.wins / (new.wins + new.losses)) * 100; return new;end;$$ language plpgsql;createor replace trigger calculate_winrate_triggerbeforeupdate on "mtg-player_deck" for each rowexecute function calculate_winrate ();
createor replace function calculate_winrate () returns trigger as $$begin new.winrate = (new.wins / (new.wins + new.losses)) * 100; return new;end;$$ language plpgsql;createor replace trigger calculate_winrate_triggerbeforeupdate on "mtg-player_deck" for each rowexecute function calculate_winrate ();
any comments or help is greatly appreciated :JinxHeart:
Solution
you are dividing two ints - you get an int as a result(rounded down). 6 / (6 + 4) * 100 -> 6 / 10 * 100 -> 0 * 100
multiply new.wins by 1.0 (not just 1) - should help. or do a coalesce to float on one of columns