Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help with formating date and sorting it descending 1

Status
Not open for further replies.

DougP

MIS
Dec 13, 1999
5,985
0
36
US
My column Week Ending Date is Datetime
Code:
Select ResourceLastName, ResourceFirstName, Manager,
convert(nvarchar(12),CAST(WeekEndDate as Date),101) as WeekEndDate, ApprovedBy
from dbo.SOWTimeReporting Where ApprovedBy = 'NotYetApproved'
Order by WeekEndDate desc
I am using the above convert... to make it into 09/15/2012. but when I sort it descending I get dates of 09/08/2012 first, since its a character, so it puts September last year first.
I want May of this year 05/21/2013 first and September last year, last.

DougP
 
Don't convert it to chars:
Code:
Select ResourceLastName,
       ResourceFirstName,
       Manager,
       CAST(WeekEndDate as Date) as WeekEndDate,
       ApprovedBy
from dbo.SOWTimeReporting Where ApprovedBy = 'NotYetApproved'
Order by CAST(WeekEndDate as Date) DESC

Borislav Borissov
VFP9 SP2, SQL Server
 
try this order by clause:

Code:
Order by CAST(dbo.SOWTimeReporting.WeekEndDate as Date) desc

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Sweet gmmastros!
simple quick, love it, have a star [thumbsup2]

DougP
 
What's interesting here is that the ORDER BY clause is the ONLY sql clause that can use column aliases. Since your table has a column named WeekEndDate and you have column in your SELECT clause aliased at WeekEndDate, the Order by uses the aliased version from your select clause.

Take a look at the following example:

Code:
Declare @Temp Table (SomeDate DateTime)

Insert Into @Temp Values('20131001')
Insert Into @Temp Values('20121101')
Insert Into @Temp Values('20131201')

-- Ordering based on select clause alias
Select Convert(nvarchar(12), SomeDate, 101) As SomeDate
From   @Temp T
Order By SomeDate

-- Ordering based on table data
Select Convert(nvarchar(12), SomeDate, 101) As SomeDate
From   @Temp T
Order By [!]T.[/!]SomeDate

Notice that the date from November is 2012 while the rest are 2013. When you run the query above you get different results even though the only difference in the query is in the order by clause. The first one orders based on month first. The second orders it by the actual date.

I only mention this because it can lead to hard to find bugs in the ordering.

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top