开发者

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


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)


If you dont want historic results, just add this:

WHERE LiveDate >= GETDATE()...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜