Beberapa saran:
- Bergabung di
seasons
sekali. Gabung menyebabkan baris dari tabel kiri diduplikasi, sehingga dapat dijumlahkan dua kali dengansum
agregat. Jika ragu, jalankan kueri tanpagroup by
untuk contoh sekolah. - Anda harus menghubungkan subquery ke outer query dengan sesuatu seperti
inner_schools.id = outer_schools.id
- Tapi sejauh yang saya lihat, Anda tidak memerlukan subquery sama sekali
Misalnya:
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
Untuk beberapa kategori, Anda dapat menggunakan kasus:
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