我的桌子上有一个到期日期列,我想按顺序提取记录。我使用了“按日期订购”的命令'但它只按降序排列日期。
使用' ORDER BY DATE'
输出2016-10-31
2016-10-06
2016-03-10
期望的输出:
2016-10-06
2016-10-31
2016-03-10
答案 0 :(得分:3)
这是你想要的吗?
order by abs(datediff(day, getdate(), [date]))
答案 1 :(得分:1)
下面的SQL中有两件事。
1) First sort by date in descending order
2) With in each month sort the dates in ascending order of day.
(以下DATEPART功能将从DATE计算DAY。)
SELECT *
FROM DATA
ORDER BY DATEPART( MONTH, date ) DESC, DATEPART( DAY, date );
答案 2 :(得分:0)
像戈登一样令人不安的辉煌,我认为有一种疏忽。
Declare @YourTable table (Date date)
Insert Into @YourTable values
('2016-10-14'), -- Added 10/14 +4 Days
('2016-10-31'),
('2016-10-06'),
('2016-03-10')
Select *, NDays=datediff(day, getdate(), [date])
From @YourTable
Order By abs(datediff(day, getdate(), [date]))
返回
Date NDays
2016-10-14 4 << Record Added (Should be below 10/6)
2016-10-06 -4
2016-10-31 21
2016-03-10 -214
我认为最安全(而且不那么优雅)会更像这样
Select *, NDays=datediff(day, getdate(), [date])
From @YourTable
Order By Year(Date) Desc,Month(Date) Desc,Day(Date)
返回
Date NDays
2016-10-06 -4
2016-10-14 4
2016-10-31 21
2016-03-10 -214