3

I have data with below format.

id     - autoincrement
myDate - timestamp

What I want to extract is get ids of for the last week.

Note By last week, I meant from Sat - Thu and not last 7 days. Considering current date (12-Feb-2013), for me, last week would be 2-Feb-2013 to 8-Feb-2013.

I know you would say, week starts from Sunday, but as I am working in Arab countries, here Friday is OFF and work starts from Saturday.

I know for last 7 days it would be just below code

BETWEEN NOW() and DATE_SUB(NOW(), INTERVAL 7 DAY)

Data at sqlfiddle

Salman A
  • 262,204
  • 82
  • 430
  • 521
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276

1 Answers1

3

Can you try below method to compute the desired result:

SELECT *,WEEKOFYEAR(dt),DAYOFWEEK(dt),DAYNAME(dt), DAYOFWEEK(NOW()),WEEKOFYEAR(NOW()) 
FROM tab1 
WHERE 1
AND 
(
  (DAYOFWEEK(NOW()) = 1 OR DAYOFWEEK(NOW()) = 6 OR DAYOFWEEK(NOW()) = 7) 
  AND 
  WEEKOFYEAR(dt) = WEEKOFYEAR(NOW()) AND DAYOFWEEK(dt) < 6
)
OR 
(    
  (DAYOFWEEK(NOW()) = 2 OR DAYOFWEEK(NOW()) = 3 OR DAYOFWEEK(NOW()) = 4  
  OR DAYOFWEEK(NOW()) = 5)
  AND
  (
     (
      (WEEKOFYEAR(dt) = WEEKOFYEAR(NOW())-2 AND DAYOFWEEK(dt) >= 6)
      OR 
      (WEEKOFYEAR(dt) = WEEKOFYEAR(NOW())-1 AND DAYOFWEEK(dt) > 1 AND DAYOFWEEK(dt) < 6)
     )
  )
);

I know this is not the smartest way, but based on this you might get hint for better solution.

Demo at sqlfiddle

Minesh
  • 2,284
  • 1
  • 14
  • 22
  • with your query I am getting data from monday to saturday. I want it from saturday to friday. :( – Fahim Parkar Feb 12 '13 at 11:26
  • @FahimParkar Yes I was working on while SqlFiddle went down, I have updated the SQL and it went down again, however it is close, it shall get you started though, please see I have hard-coded date to check the various scenario, but you can test that once done, replace hard-coded '2013-02-10' with NOW() function – Minesh Feb 12 '13 at 12:45
  • can you have sqlfiddle solution with `NOW()`? – Fahim Parkar Feb 12 '13 at 13:39
  • @FahimParkar It is there with NOW() option but You are expected to change yourself to test :) – Minesh Feb 12 '13 at 15:25