Monday, March 26, 2012

Order By for DATENAME

SELECT DATENAME(mm,w1.WorkoutDate) AS WorkoutMonth,
DATEPART(yyyy,w1.WorkoutDate) AS WorkoutYear,
Count(*) AS WorkoutDaysCount
FROM Workout w1
WHERE w1.MemberID = @.Memberid
GROUP BY DATENAME(mm,w1.WorkoutDate),DATEPART(yyyy,w1.WorkoutDate)

how do i implement order by in above query? I want the result month & year wise. i'm using DATENAME function here.

Try the following

SELECT DATENAME(mm,w1.WorkoutDate) AS WorkoutMonth,

DATEPART(yyyy,w1.WorkoutDate) AS WorkoutYear,

Count(*) AS WorkoutDaysCount

FROM Workout w1

WHERE w1.MemberID = @.Memberid

GROUP BY DATEPART(m,w1.WorkoutDate),DATENAME(mm,w1.WorkoutDate),DATEPART(yyyy,w1.WorkoutDate)

order by DATEPART(yyyy,w1.WorkoutDate)

,DATEPART(m,w1.WorkoutDate)

|||

One more question. i have table named [WorkoutCount] with month,year and other columns. I'm storing month as integer. But when i retreive data i wanted charchter month like "April" instead of 5. How do i use DATENAME in this case or is there any alternate solution?

|||Select DateName(Month, MonthColumnName) from Table|||

Select DateName(Month, MonthColumnName) from Table

this is not workking. for example select DATENAME(mm,2) should return february but it always returns january

|||

The 2nd argument to datename has a type of datetime not integer. That is, you should perform your select:

select datename (mm, '2/1/2007')

and not

select datename (mm, 2)


Dave

No comments:

Post a Comment