How do I go about making the in_date’s end date always based on the previous week’s last date?
For example today is 24 April 2023, and the previous week’s (Mon to Sun) last date was 16/04/2023
Expected SQL Query:
SELECT ga.in_date,
FROM in_txn ga
LEFT JOIN cntr_mst cm ON cm.cntr_num = ga.cntr_num
WHERE status_active = 'A'
and (in_date between '2020-01-01 00:00:00' and '2023-4-16 23:59:59')
2
Answers
I suggest this:
Also:
between
is painful! as "23:59:59" might not be the last moment of the day (the maximum precision of a MySQL TIMESTAMP column is up to microseconds , 6 digits) so it is so much easier – and more reliable – to avoid using it. Note that I have moved the second date up one second.see: https://dbfiddle.uk/DL-cJL8n
You want to filter from the beginning of year 2020 to the end of last week.
We can compute the date of the last Monday (or today if it’s a Monday) with
current_date
andweekday()
:And we can use this expression to filter with a half-open interval, voilà!