Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by Month, Day closest to now

I am writing a statement to pull accounts that are due the soonest. My query currently sorts on month and day as year is irrelevant. Is there anyway to set the current month and day as the top most values? rather than jan 01?

SELECT *
FROM clients
WHERE LiveDate IS NOT NULL
Order by DATEPART(month, LiveDate), DATEPART(day, LiveDate)

Would I just need to split it into two queries one looking for after the current month day, one looking for before, and join them so that they are in the right order

EXAMPLE:

date founded || Annual function
01/01/2011   || beach outing
11/03/2010   || family day
23/03/2009   || Movies
05/04/2000   || Girls night out
10/05/2005   || Cricket function
29/07/2011   || candle lit formal dining
30/07/2008   || childrens day
04/08/2005   || board games day
03/012/2006  || pizza night
20/012/2001  || camping trip

As this is an annual outing the year does not matter. I want to pull them in order of the event closest to now through to the end of the year, then from the start of the year through to today.

so the results would be in this order based on a current day of: 23/06/2011

date founded || Annual function 
29/07/2011   || candle lit formal dining 
30/07/2008   || childrens day 
04/08/2005   || board games day 
03/012/2006  || pizza night 
20/012/2001  || camping trip              _ _ _ _ _ _ _ New year _ _ _ _ _  
01/01/2011   || beach outing 
11/03/2010   || family day 
23/03/2009   || Movies 
05/04/2000   || Girls night out 
10/05/2005   || Cricket function
like image 890
Rumpleteaser Avatar asked Apr 24 '26 19:04

Rumpleteaser


1 Answers

SELECT *
FROM clients
WHERE LiveDate IS NOT NULL
ORDER BY ABS(DATEDIFF(day, LiveDate, GETDATE())

UPDATE

Sorry, didn't get it at first that only the proximity to the current day and month, but not year, should be taken into account when sorting.

So maybe like this:

SELECT *
FROM clients
WHERE LiveDate IS NOT NULL
ORDER BY
  ABS(
    DATEDIFF(
      day,
      DATEADD(year, DATEDIFF(year, LiveDate, GETDATE()), LiveDate),
      GETDATE()
    )
  )

?


UPDATE 2

Based on the examples provided, this should do the job:

…
ORDER BY
  (MONTH(LiveDate) - MONTH(GETDATE()) + 12) % 12,
  DATEADD(year, YEAR(GETDATE()) - YEAR(LiveDate), LiveDate),
  YEAR(LiveDate)
like image 95
Andriy M Avatar answered Apr 27 '26 10:04

Andriy M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!