0

I have Donaters table:

id,name,phone,address

And Donations table:

id,donater_id,donation_amount

what I want is to get all donaters with their max donation amount like this:

id,name,donation_amount

I have tried the following query to get the result.

select a.id,a.name,max(b.donation_amount) max_d 
from donaters a left join donations b on b.donater_id = a.id 
groub by a.id,a.name,max_d 

However, it returns duplications.

atokpas
  • 3,231
  • 1
  • 11
  • 22
BecauseGeek
  • 17
  • 1
  • 1
  • 6
  • 1
    Did you try something on your own? – atokpas Oct 03 '17 at 06:46
  • i tried this:: select a.id,a.name,max(b.donation_amount) max_d from donaters a left join donations b on b.donater_id = a.id groub by a.id,a.name,max_d but it returns duplications – BecauseGeek Oct 03 '17 at 06:55

3 Answers3

1

Simply use GROUP BY and MAX

  SELECT dr.id, dr.name, MAX(ds.donation_amount) as donation_amount
  FROM donaters dr
  JOIN donations ds On dr.id = ds.donater_id
  GROUP BY dr.id, dr.name

This solution will miss the donators who did not donated anything. If you need such donators use LEFT JOIN and ISNULL function.

Radim Bača
  • 10,646
  • 1
  • 19
  • 33
0

This should work just fine, a Basic left outer join on the basis of the id and then aggregate max function on donation_amount.

SELECT a.id,a.name,max(donation_amount) from Donaters a
LEFT outer JOIN Donations b
ON a.id=b.id
group by a.id,a.name
Jayesh Mulwani
  • 655
  • 6
  • 19
0
select Dtrs.Id ,Dtrs.name,MAX_Donations.donation_amount from  
         Donaters Dtrs left join (
Select Dtrs.id Dtrs_id ,Max(Dons.donation_amount) donation_amount  from Donations Dons 
         inner join Donaters Dtrs on Dons.donater_id = Dtrs.id 
Group By Dtrs.id) Max_Donations on Max_Donation.Dtrs_id = Dtrs.id

Here for more information

Arsalan
  • 709
  • 2
  • 14
  • 27