Question :
I got this table list:
table pinjam
kd_pinjam(primary) | norek | tgl_pinjam | jml_angsuran | jml_pinjam | sisa
pin-0001 | 7811088313831 | 2020-12-20 | 10 | 5000000 | 10
table riwayat_pinjam
kd_pinjam(primary) | norek | jml_pinjam | angsuran | gagal_bayar | tgl_lunas
pin-0001 | 7811088313831 | 5000000 | 10 | 0 | null
I want to create a monthly report, for customers that have loan in a certain month (ex: January)
This is syntax that I use:
SELECT sum(pinjam.jml_pinjam) as pinjam
from pinjam
left join riwayat_pinjam
on pinjam.kd_pinjam = riwayat_pinjam.kd_pinjam
where month(tgl_pinjam) BETWEEN month('2020-12-01') and month('2021-02-28')
But the result I get is that pinjam
is null. I expect pinjam
to equal 5000000.
What is wrong with my query?
Answer :
x BETWEEN a AND b
translates to x >= a AND x <= b
. In your case a
is 12 and b
is 2; there is nothing that is simultaneously greater than 12 and less than 2, so no rows match.
This will avoid most issues:
where tgl_pinjam >= '2020-12-01'
AND tgl_pinjam < '2020-12-01' + INTERVAL 3 MONTH
Even without worrying about leap year.