Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the data of the last week from (Monday to Sunday)

I would like to get the data from the last week. A week is Monday to Sunday.

I made this query :

    sql = 'SELECT COUNT(*) ' \
          'FROM panelname ' \
          'WHERE year(date) = year(now()) ' \
          'AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() '
    cursor.execute(sql)
    test = cursor.fetchall()
    print(test)

The problem with AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() is that it takes the data from the past 7 days. If I am Tuesday of the current week and I run it, I will get the data from last week’s Tuesday up until this week’s Tuesday, which is not what I want. It should give the data from last Monday down to last Sunday.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I also precise that it should not use the DATEADD function, because I don’t have the admin rights to use it.

For example : I run the query today, it doesn’t matter which day we are, and I get the last week of data (Monday to Sunday).

Thank you.

>Solution :

You must first get the most recent Monday and use it as a reference point to calculate the 5 previous weeks:

SELECT COUNT(*)
FROM panelname
WHERE date >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) day - INTERVAL 5 week
AND date < CURDATE() - INTERVAL WEEKDAY(CURDATE()) day
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading