Chris Chris - 7 months ago 12
SQL Question

I get duplicates from this SQL query and I think it should just add them up

Here is my code

select
name, sum(Value) as [Total Donated]
from
CHARITY c
join
DONATION d on c.CharityID = d.CharityID
join
ITEM_DONATION id on d.DonationID = id.DonationID
group by
name, DonationDate
having
DonationDate like '%13%'
order by
name;


and the output

name Total Donated
-------------------- -------------
Boy Scouts 250.00
Boy Scouts 5.00
Focus Hope 5.00
Focus Hope 10.00
Fresh Start Charity 12.00
Helping Hands 2.99
Helping Hands 12.50
Helping Hands 110.50
St. John Hospital 112.00


I thought I had it set where the Boy Scouts should be one item just added together and same with focus hope and etc.... but I am a bit off somewhere can anyone help and let me know what I'm doing wrong here?

Answer

You need to remove DonationDate from the GROUP BY clause and move the condition from HAVING into the WHERE clause:

select 
    name
    , sum(Value) as [Total Donated]
from CHARITY c 
join DONATION d
    on c.CharityID = d.CharityID
join ITEM_DONATION id
    on d.DonationID = id.DonationID
where
    DonationDate like '%13%'
group by name
order by name;