我正在写一份声明来提取最快到期的帐户。我的查询目前按月和日排序,因为年份无关紧要。无论如何将当前月份和日期设置为最高值?而不是jan 01?
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
答案 0 :(得分:7)
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)
答案 1 :(得分:0)
如果你不想要历史性的结果,只需添加:
WHERE LiveDate >= GETDATE()...