我正在写一个声明来提取最快到期的帐户。我的查询目前按月和日排序,因为年份无关紧要。无论如何,可以将当前月份和日期设置为最上面的值吗? 而不是01年1月?
SELECT *
FROM clients
WHERE LiveDate IS NOT NULL
Order by DATEPART(month, LiveDate), DATEPART(day, LiveDate)
我只需要将其拆分为两个查询,一个在当前月份之后查找,一个在当前月份日期之前查找,然后连接它们,以便它们按正确的顺序排列
例:
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
由于这是一年一度的郊游,因此年份无关紧要。我想按照最接近现在到年底的事件顺序拉动它们,然后从年初到今天。
因此,结果将按以下顺序排列,基于当前日期: 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())
更新
抱歉,一开始没有明白,排序时只应考虑与当前日期和月份的接近程度,而不是年份。
所以也许像这样:
SELECT *
FROM clients
WHERE LiveDate IS NOT NULL
ORDER BY
ABS(
DATEDIFF(
day,
DATEADD(year, DATEDIFF(year, LiveDate, GETDATE()), LiveDate),
GETDATE()
)
)
?
更新 2
根据提供的示例,这应该可以完成工作:
…
ORDER BY
(MONTH(LiveDate) - MONTH(GETDATE()) + 12) % 12,
DATEADD(year, YEAR(GETDATE()) - YEAR(LiveDate), LiveDate),
YEAR(LiveDate)
如果您不想要历史结果,只需添加以下内容:
WHERE LiveDate >= GETDATE()...