I am trying to get a list of donors who have cumulatively donated $5K between two different campaigns. My data is something like this
Attributes table
| transactionid | attributevalue |
|---|---|
| 123231 | campaign 1 |
| 123456 | campaing 2 |
| 123217 | campaign 1 |
| 45623 | campaing 2 |
| 65791 | campaing 3 |
| 78931 | campaign 4 |
| 11111 | campaign 5 |
| 22222 | campaing 6 |
Donations table
| transactionid | donationamount | donorid |
|---|---|---|
| 123231 | 2000 | 1233 |
| 123456 | 30000 | 1456 |
| 45623 | 8000 | 1233 |
| 78931 | 90 | 8521 |
| 11111 | 20 | 1233 |
| 22222 | 68 | 1456 |
Donor table
| donorid | name |
|---|---|
| 1233 | John |
| 1456 | Mary |
| 8521 | Karl |
This is what I tried, but the total I am getting is not right at all.
WITH test AS (
SELECT don.donorid,don.donationamount,a.attributevalue
FROM attributes table a
INNER JOIN donations don ON don.transactionid=a.transactionid
)
SELECT d.donorid,
SUM(CASE WHEN test.attributevalue='campaign 1' OR test.attributevalue='campaign 2'
THEN test.donationamount END) AS campaing_donation,
SUM(test.donationamount) AS total_donations
FROM donortable d
INNER JOIN test ON d.donorid = test.donorid
GROUP BY d.donorid
HAVING SUM(CASE WHEN test.attributevalue = 'campaign 1' OR test.attributevalue = 'campaign 2' THEN test.donationamount END) > 5000
but this is not working. My total donations sum is giving a value that is several times higher than the actual value.
Ideally, the final result would be something like this:
| donorid | campaign_amount | totalamount |
|---|---|---|
| 1233 | 10000 | 10020 |
| 1456 | 30000 | 30068 |
CodePudding user response:
Select
sum (Donations.donationamount),
donor.donorid,
donor.name
from
Attributes
join Donations on
Donations.transactionid = attributes.transactionid
Join Donor on
donor.donorid = donations.donorid
Where
Attribute.attributevalue in ('campaign 1','campaign 2')
Group by
donor.donorid,
donor.name
CodePudding user response:
create table #transection_tbl(tran_id int,attributevalue varchar(20))
create table #donation_tbl(tran_id int,donation_amount int ,donar_id int)
select donar_id,max(donation_amount) as 'campaing_amount',
sum(donation_amount) as 'totalamount'
from #transection_tbl as t1
inner join #donation_tbl as t2 on t1.tran_id=t2.tran_id
group by donar_id
having COUNT(attributevalue)=2
