I am developing a website for a charity where amounts are pledged by individuals and recorded into a table. The individuals belong to a group. The payments received are recorded in another table however they are tagged to a group leader and not an individual. There can be multiple payments to reach the pledged amount.
I wanted an SQL query that would compare the amounts pledged by a group with the payments tagged to the group leader. My Tables are as follows:
Donor Table
id | group_leader_id | name |
---|---|---|
1001 | 1001 | John |
1002 | 1001 | Steve |
1003 | 1001 | Richard |
1004 | 1004 | Paul |
1005 | 1004 | Stacy |
1006 | 1004 | Lucy |
Pledged Table
id | amount | year |
---|---|---|
1001 | 20 | 2023 |
1002 | 25 | 2023 |
1003 | 10 | 2023 |
1004 | 15 | 2023 |
1005 | 40 | 2023 |
1006 | 50 | 2023 |
Payment Table
id | amount | year |
---|---|---|
1001 | 10 | 2023 |
1001 | 10 | 2023 |
1001 | 20 | 2023 |
1001 | 15 | 2023 |
1004 | 35 | 2023 |
1004 | 35 | 2023 |
1004 | 35 | 2023 |
I have created two queries with sum but how can i compare them to check if the amount that has been pledged has been paid?
query1
SELECT Donor.Name Donor.id , SUM(Pledged.amount)
FROM Donor , Pledged
WHERE Donor.id = Pledged.id
AND year = '2023'
GROUP BY group_leader_id
query2
SELECT Donor.id , SUM(Payment.amount)
FROM Payment
WHERE year = '2023'
GROUP BY Donor.id
4
Answers
Here is An Example:
This query provides a clear comparison of pledged and paid amounts for each group, making it easy to track payment status and identify any outstanding balances.
You can JOIN the two queries like this:
see: DBFIDDLE
You might need to change some small things, but that’s because no desired output was given in your question …. 😢
With this structure you can’t assign a payment to an individual pledge.
This means that your aggregate output would presumably be the amount Pledged per group leader, vs the amount Paid per group leader.
That I need to presume that is one reason you’ve gotten such poor engagement for your question. Please ensure you include the expected results in your questions, as per the [mre] help page.
https://dbfiddle.uk/0u76nmpv
Result:
db<>fiddle.