Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring the year in SQL Query with date range

Tags:

sql

mysql

Normally if I want to make a query on a table by date range I'll do it this way:

SELECT DISTINCT c.ID AS 'id' FROM CUST c 
JOIN TICKET t ON s.ID = t.SALE_ID 
WHERE c.ACTIVE_IND = 1 
AND t.DELIV_DATE BETWEEN '01-01-2012' AND '01-02-2012'
ORDER BY t.DELIV_DATE DESC

Now I need to make the same query but ignore the year, so I can say from February 28 to March 2 and year doesn't matter.

I tried modifying the query:

SELECT DISTINCT c.ID AS 'id' FROM CUST c 
JOIN TICKET t ON s.ID = t.SALE_ID 
WHERE c.ACTIVE_IND = 1 
AND MONTH(t.DELIV_DATE) BETWEEN  ... AND ... 
AND DAY(t.DELIV_DATE) ... BETWEEN ...
ORDER BY t.DELIV_DATE DESC 

Above query works fine if the starting DAY is smaller than the ending. that means if I go from lets say Feb 20 to Feb 28 it works fine but if I go with Feb 28 to Mar 2 it won't work.

Any solution for this that I can make this happen in a single query ?

like image 213
Tohid Avatar asked Feb 28 '12 23:02

Tohid


1 Answers

...
AND DATE_FORMAT(t.DELIV_DATE, '%m%d') BETWEEN '0101' AND '0201'
...

Update - to handle range that loops though the end year (replace 0101 and 0201 with actual variables representing from and to):

...
AND
  (DATE_FORMAT(t.DELIV_DATE, '%m%d') BETWEEN '0101' AND '0201'
   OR '0101' > '0201' AND
     (DATE_FORMAT(t.DELIV_DATE, '%m%d') >= '0101' OR
      DATE_FORMAT(t.DELIV_DATE, '%m%d') <= '0201'
     )
  )
...
like image 171
Aprillion Avatar answered Oct 06 '22 23:10

Aprillion