2

I have an expiration date column on my table, I want to fetch records in order that are nearly to expire. I used 'ORDER BY DATE DESC' but it only arranges the date in descending order.

Output using 'ORDER BY DATE'

2016-10-31
2016-10-06
2016-03-10

desired output:

2016-10-06
2016-10-31
2016-03-10
7
  • 3
    What is the logic for desired output? Commented Oct 11, 2016 at 2:27
  • He wants the data to be sorted in descending order of months and ascending order of days with in each month. Commented Oct 11, 2016 at 2:32
  • fetch records that is near on the date today. Commented Oct 11, 2016 at 2:36
  • Can you be more specific.... Commented Oct 11, 2016 at 2:38
  • as what you have mentioned @Teja. "sorted in descending order of months and ascending order of days with in each month" this is the logic of the output Commented Oct 11, 2016 at 2:44

3 Answers 3

3

Is this what you want?

 order by abs(datediff(day, getdate(), [date]))
Sign up to request clarification or add additional context in comments.

3 Comments

by the way sir, what is abs?
@MDP - ABS converts all the values to positive values. Here is a official documentation link msdn.microsoft.com/en-us/library/ms189800.aspx
Check my answer
1

There are two things in the below SQL.

1) First sort by date in descending order
2) With in each month sort the dates in ascending order of day.

( The below DATEPART function will calculate the DAY from DATE. )

SELECT * 
  FROM DATA
ORDER BY DATEPART( MONTH, date ) DESC, DATEPART( DAY, date );

3 Comments

alias in order by? and btw, sql server doesn't have extract function.
it doesn't work. same output using order by date desc.
Try now.. I am extracting month and sorting in desc order then sorting data in ascending order of day
0

As disturbingly brilliant as Gordon is, I think there was an oversight.

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]))

Returns

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

I think the safest (and far less elegant) would be something more like this

Select *, NDays=datediff(day, getdate(), [date]) 
From @YourTable
Order By Year(Date) Desc,Month(Date) Desc,Day(Date)

Returns

Date        NDays
2016-10-06  -4
2016-10-14  4
2016-10-31  21
2016-03-10  -214

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.