Tuesday, March 1, 2011

How do I form an SQL query using DATE_SUB to check for yesterday's data OR if it's Monday, to check for Friday's data?

Here's my query:

SELECT *
FROM daily_records 
AND date = DATE_SUB(CURDATE(), INTERVAL 1 DAY)

I use this to generate a report of everything that happened yesterday. This works great, Tuesday-Friday. However, on Mondays, I want it to be able to search back to Friday (the previous business day, eg INTERVAL 3 DAY).

Is there a way to do this in mySQL? Or do I just need to check the day of the week in PHP before writing the query?

From stackoverflow
  • You could do...

    SELECT *
    FROM daily_records
    WHERE date = IF(DAYOFWEEK(CURDATE()) = 2, DATE_SUB(CURDATE(), INTERVAL 3 DAY), DATE_SUB(CURDATE(), INTERVAL 1 DAY))
    
    Greg : Same-second answers!
  • This should do it:

    SELECT * FROM daily_records AND date =
    DATE_SUB(CURDATE(), INTERVAL IF(DATE_FORMAT(NOW(), '%w') = 1, 3, 1) DAY)
    
    Jen : I like this ... I think I need to change the 5 in the if statement so it reads: IF(DATE_FORMAT('%w', NOW()) = 1, 3, 1) because NOW() would be Monday, not Friday. Thanks!
    Jen : Another note - I just researched DAYOFWEEK() and DATE_FORMAT() and they use different indexes. With DAYOFWEEK(), Sunday=1. With DATE_FORMAT(), Sunday=0. Anyone know why?!?
    Greg : That's true... DAYOFWEEK follows ODBC, DATE_FORMAT follows... ISO?
    Jen : This is mostly just a note to myself, but possibly helpful to others as well ... the parameters for the date_format function are backwards. It should be DATE_FORMAT(NOW(), '%w') ...
    Greg : Oops - fixed, thanks
  • mysql> create function PREV_BIZ_DATE ()
        -> returns DATE
        -> return (CURRENT_DATE() - interval if(DAYOFWEEK(CURRENT_DATE()) = 2, 3, 1) day);
    
    mysql> SELECT * FROM daily_records WHERE date = PREV_BIZ_DATE();
    

0 comments:

Post a Comment