Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 453
  • Last Modified:

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!
0
dingir
Asked:
dingir
  • 2
1 Solution
 
Patrick MatthewsCommented:
Because    is always null :)In SQL Server:select sum(table1.amount - COALESCE(table2.prize, 0)) as houseWin  from table1  left join table2 on table1.id = table2.table1idAccess:select sum(table1.amount - Nz(table2.prize, 0)) as houseWin  from table1  left join table2 on table1.id = table2.table1id
0
 
dingirAuthor Commented:
Im not sure what u mean with the first statement but coascale did it :)
0
 
Patrick MatthewsCommented:
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
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now