Link to home
Start Free TrialLog in
Avatar of dingir
dingirFlag for Sweden

asked on

Left Join and Sum()

I though this was basic but some help are needed..

I do a left join because there MIGHT exist records in table2.

 select table1.amount, table2.prize
 from table1
 left join table2 on table1.id = table2.table1id

My problem begins here,
 select sum(table1.amount - table2.prize) as houseWin
 from table1
 left join table2 on table1.id = table2.table1id

Sum is removing all records that does not corresponds in table2.
Sum() goes totally wrong when grouping records.

WANT THIS
IF amount and prize exist the result is, do (amount-prize)
IF there aren't a prize (returns null in left join) the result is (amount-0)

Help!
ASKER CERTIFIED SOLUTION
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dingir

ASKER

Im not sure what u mean with the first statement but coascale did it :)
dingir,Glad to help :)What I meant was that in your original query, you have some instances where there is a number for table1.amount, but table2.prize was null.  Any time you try to perform an operation where at least one side is null, the result will be null.COALESCE worked because it substituted a non-null value, in this case zero, any time table2.prize was null.Patrick