Nogle forslag:
- Deltag på
seasons
enkelt gang. En joinforbindelse får rækker fra den venstre tabel til at blive duplikeret, så de kan summeres to gange medsum
samlet. Hvis du er i tvivl, så kør forespørgslen udengroup by
for et eksempel på en skole. - Du skal relatere underforespørgslen til den ydre forespørgsel med noget som
inner_schools.id = outer_schools.id
- Men så vidt jeg kan se, behøver du slet ikke en underforespørgsel
For eksempel:
SELECT schools.*
, sum(cashflows.amount) total_branding_cashflow
FROM schools
JOIN seasons
ON seasons.school_id = schools.id
and seasons.year = 2010
JOIN cashflows
ON cashflows.season_id = seasons.id
and cashflow_group_id = 12
GROUP BY
schools.id
HAVING total_branding_cashflow BETWEEN 50000000 AND 100000000
For flere kategorier kan du bruge en sag:
SELECT schools.*
, sum(case when cashflow_group_id = 1 then cashflows.amount end) total1
, sum(case when cashflow_group_id = 12 then cashflows.amount end) total12
FROM schools
JOIN seasons
ON seasons.school_id = schools.id
and seasons.year = 2010
JOIN cashflows
ON cashflows.season_id = seasons.id
GROUP BY
schools.id