How to set SQL to find records from last sunday to this sunday (1 week)

后端 未结 1 708
一生所求
一生所求 2021-01-13 08:26

This is similar to what I have now, which is:

SELECT COUNT(author) FROM `posts` WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) AND author=\'FooBar\'

相关标签:
1条回答
  • 2021-01-13 09:05

    To get the latest preceding sunday midnight, this should do it. Replace both instances of NOW() with your datetime to check another date.

    SELECT DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY) latest_sun
    

    To get the sunday one week earlier, instead use DAYOFWEEK(NOW())+6 DAY.

    EDIT: That'd make your query;

    SELECT COUNT(author)
    FROM `posts` 
    WHERE author='FooBar'
      AND `date` >= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY)
      AND `date` <  DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY)
    
    0 讨论(0)
提交回复
热议问题