Using SQL Server 2008…
I’m having some troubles in trying to order my rows in a specific order that I would like them to be ordered by. I’ve found a few examples that use the ORDER BY CASE clause, but am unsure whether using this method will produce the result that I want it to, thus I come to the community!
Here’s what I have:
First, I select, if it exists, a distinct year that is equal to the current year:
IF EXISTS(SELECT DISTINCT [Year]
FROM Assessment WHERE ProjectCode = @ProjectCode AND [Year] = DATENAME(YEAR, GETDATE()))
SELECT DISTINCT [Year]
FROM Assessment WHERE ProjectCode = @ProjectCode
But, then I find some confusion in ordering the results. I’d like to set the current year to the first row returned using the ORDER BY clause, then order the rest of the returned years in a descending order, here’s what I have so far:
ORDER BY (CASE WHEN [Year] = (DATENAME(YEAR, GETDATE())) THEN 1
ELSE 100 END) ASC, [Year] desc
Next, if the current year is not contained in the query, select each year and order by year descending.
ELSE
SELECT DISTINCT [Year]
FROM Assessment WHERE ProjectCode = @ProjectCode
ORDER BY [Year] desc
Thanks, in advance!
You’re question isn’t very clear because you don’t specify what is broken or where you’re having issues. From what I gather, however, you don’t need an IF/ELSE. Instead you could do something like …
FYI … i added the case to the select list as a throw away column to avoid the error I assume you’re getting.. There are other ways, like a derived table, but for now this should work..
HTH,
-eric