I have the following four tables: region_reference, community_grants, HealthWorkers and currency_exchange
and the follow SQL query which works:
SELECT HealthWorkers.worker_id
, community_grants.percentage_price_adjustment
, community_grants.payment_status
, community_grants.chosen
, (region_reference.base_price * currency_exchange.euro_value) AS price
FROM currency_exchange
INNER JOIN (
region_reference INNER JOIN (
HealthWorkers INNER JOIN community_grants
ON HealthWorkers.worker_id = community_grants.worker_id
) ON (
region_reference.community_id = community_grants.community_id
) AND (region_reference.region_id = community_grants.region_id)
)
ON currency_exchange.currency = HealthWorkers.preferred_currency
WHERE (
HealthWorkers.worker_id="malawi_01"
AND community_grants.chosen=True
);
It gives me the following result set:
However, my task is to create an entity that includes just 4 values.
type OverallPriceSummary struct {
Worker_id string `json:"worker_id"`
Total_paid decimal.Decimal `json:"total_paid"`
Total_pledged decimal.Decimal `json:"total_pledged"`
Total_outstanding decimal.Decimal `json:"total_outstanding"`
}
Total_paid is the sum of values for the specified worker_id where payment_status = “1” (combined for all records)
Total_outstanding is the sum of values where payment_status is “0” and chosen is true (combined for all records)
Total_pledged is the sum of Total_paid and Total_outstanding (also combined for all records)
I currently obtain these values by aggregating this manually in my code as postgresql iterates through the resultset but I believe there is a way to avoid this interim SQL query and get what I need from a single SQL query. I suspect it involves the use of SUM AS and inner queries but I don’t know how to bring it all together. Any help or direction would be much appreciated.
EDIT: I have provided some sample data below:
region_reference
| region_id | region_name | base_price | community_id |
|---|---|---|---|
| 1 | Lilongwe | 100 | 19 |
| 2 | Mzuzu | 50 | 19 |
HealthWorkers
| worker_id | worker_name | preferred_currency | billing_address | charity_logo |
|---|---|---|---|---|
| malawi_01 | Raphael Salanga | EUR | Nkhunga Health Centre in Nkhotakota District | 12345 |
community_grants
| region_id | campaign_id | worker_id | percentage_price_adjustment | community_id | payment_status | chosen | paid_price |
|---|---|---|---|---|---|---|---|
| 1 | 1 | malawi_01 | 10 | 19 | 0 | Yes | 0 |
| 2 | 1 | malawi_01 | 0 | 19 | 1 | Yes | 20 |
| 3 | 1 | malawi_01 | 1 | 19 | 0 | Yes | 0 |
| 1 | 1 | malawi_01 | 0 | 23 | 0 | Yes | 30 |
currency_exchange
| currency | currency_symbol | euro_value |
|---|---|---|
| EUR | € | 1 |
| USD | $ | 0.84 |


region_reference.base_price * currency_exchange.euro_value) AS price?