I have the following query: (sample schema here: https://www.db-fiddle.com/f/5e9gVC6oRidjYwigPWRKm/3)
SELECT
t.customer_id
, t.ticket_id
, c.combination_id
, c.possible_prize + c.confirmed_prize + coalesce(cb.bonus_amount,0) AS won_amount
, round(mul(o.value)::numeric,3) AS odds
FROM tickets t
JOIN combinations c ON c.ticket_id = t.ticket_id
LEFT JOIN combination_bonus cb ON cb.combination_id = c.combination_id
JOIN outcomes o ON o.ticket_id = t.ticket_id AND o.outcome_id = ANY(c.outcomes)
GROUP BY 1,2,3, cb.bonus_amount
ORDER BY 1
Without + coalesce(cb.bonus_amount,0)
it runs fine, why only this column need to grouped, not the two others in this equation?
Also if I would put this line into sum() the results would be totally wrong as it is going to be multiplied few times, and I don't get it why and how.
Would much appreciate explanation on both cases.