Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Dynamic Sorting Issue

Author  Topic 

james.burger
Starting Member

4 Posts

Posted - 2010-02-01 : 10:11:18
I solved my own question.

I used:
SELECT TOP 100 PERCENT semester, begindate, enddate, (CASE WHEN DATEDIFF(dd, GETDATE(), enddate) > 0 THEN DATEDIFF(dd, GETDATE(), enddate)
ELSE DATEDIFF(dd, GETDATE(), enddate) + 10000 END) AS Dates
FROM dbo.tbl_SDFRSperiods
ORDER BY Dates

james.burger
Starting Member

4 Posts

Posted - 2010-02-01 : 12:12:04
quote:
Originally posted by james.burger

I am trying to sort on Semesters, with the closest semester being returned as the first on the list and the previous semesters appear towards the end of the list.

I currently have the following: SELECT TOP 100 PERCENT semester, begindate, enddate, DATEDIFF(dd, GETDATE(), enddate) AS Dates
FROM dbo.tbl_SDFRSperiods
ORDER BY DATEDIFF(dd, GETDATE(), enddate)

My semesters are: Fall 2009 (8/15/2009 - 12/31/2009), Spring 2010 (1/1/2010 - 6/30/2010), Summer 2010 (7/1/2010 - 8/14/2010), and Fall 2010 (8/15/2010 - 12/31/2010).

The above query gives me Fall 2009, Spring 2010, Summer 2010, Fall 2010. But I would like the query to dynamically sort the semesters based upon the current date. So today is 2/1/2010, the sort would produce Spring 2010, Summer 2010, Fall 2010, and Fall 2009.

On 7/1/2010, the sort would produce Summer 2010, Fall 2010, Fall 2009, Spring 2010.

I tried the following:
SELECT TOP 100 PERCENT semester, begindate, enddate, DATEDIFF(dd, GETDATE(), enddate) AS Dates
FROM dbo.tbl_SDFRSperiods
ORDER BY (CASE Dates WHEN Dates > 0 THEN Dates ELSE Dates + 10000 END) ASC

But I am having no luck. Thanks!


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-02-01 : 12:20:27
try like ORDER BY CASE WHEN GETDATE() BETWEEN begindate AND enddate THEN 0 ELSE 1 END,DATEDIFF(dd, GETDATE(), enddate)
Go to Top of Page
   

- Advertisement -