views:

56

answers:

6

How can I select the hour from a datetime?

I'm looking for the equivalent of Oracle's TO_CHAR( d, 'HH24' ), which would return 17 for 2010-06-23 17:22:31.


I tried to find out about the best time (best answer/questin-ration) to ask an SQL-related question on StackOverflow, using Data Explorer. I got it to work, but I'm sure there is a more elegant version.

Select
  Left( Convert(VARCHAR(10), creationDate, 8 ), 2 ) As hour,
  Convert(Float, Count(*)) / Count(Distinct p.parentId) As ratio
From posts p
Join postTags pt On ( pt.postId = p.parentId )
Join tags t On ( t.id = pt.tagId )
Where p.postTypeId = 2 And t.tagName = '##TagName##'
Group By Left( Convert(VARCHAR(10), creationDate, 8 ), 2 )
Order BY hour

BTW, the best time seems to be between 15:00 and 16:00 - guess I'm asking too late :)

alt text

+1  A: 

Use the DatePart() tsql function with the part ID of "hour"

Look at this for a good explanation

http://support.microsoft.com/kb/186265

Paul Mendoza
Thanks for the additional link (`+1`)
Peter Lang
+3  A: 

Use DATEPART

select DATEPART(hour, DateTimeField) as Hour from Table
Adam Robinson
Ah, thanks. That's what I was looking for.
Peter Lang
+1  A: 

This should work

SELECT DatePart(hh, GETDATE()) 
Baaju
Yes, that works too (`+1`)
Peter Lang
A: 

datepart(hh,dateColumn) should get you the hour component for any datetime.

Jim Dagg
A: 
SELECT HOUR(datetimefield) AS hour

The HOUR() function should do the job. Source http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_hour.

Richards
Sorry, but that doesn't seem to work. Looks like you are citing the `MySQL` documentation.
Peter Lang
Oops, I didn't notice you have a full datetime, though you only have time.
Richards
A: 
Select DatePart(hh, CreationDate) As Hour
    , Convert(Float, Count(*)) / Count(Distinct p.parentId) As Ratio
From posts As p
    Join postTags As pt 
        On ( pt.postId = p.parentId )
    Join tags As t 
        On ( t.id = pt.tagId )
Where p.postTypeId = 2 
    And t.tagName = '##TagName##'
Group By DatePart(hh, CreationDate)
Thomas