views:

1242

answers:

6

How do i convert hh:mm:ss to hh:mm in sql server?

select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog   
where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58'  
and [user] in(select USERNAME             
    from scr_CustomerAuthorities )  
group by Page,Date order by [VisitingCount] asc  
+4  A: 

In general, the set of timestamps is not well-ordered, this means you cannot get a "last" timestamp whose time part up to minutes is 2009-05-06 14:58.

In SQL Server, which keeps the time part of a datetime as a number of 1/300 second fractions after midnight, this "last" timestamp would be 2009-05-06 14:58:59.997, but this is not guaranteed to be compatible with future releases of with other TIMESTAMP storage methods.

That means you'll need to split your BETWEEN condition into two conditions, one of which being strict less than the next minute:

select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog   
where Date >= '2009-05-04 00:00:00'
      AND Date < DATEADD(minute, 1, '2009-05-06 14:58')
and [user] in(select USERNAME             
    from scr_CustomerAuthorities )  
group by Page,Date order by [VisitingCount] asc

This solution will efficiently use indexes on Date

Quassnoi
A: 

For this specific need you should use the between method as noted by Quassnoi's answer. However, the general problem can be solved with:

select dateadd(second, -datepart(second, @date), @date)
Mehrdad Afshari
A: 

I dont think there is a built in function; usually do something like this

SET @time = '07:45'
SET @date = CONVERT(DATETIME,@time)
SELECT @date

SELECT LEFT(CONVERT(VARCHAR,@date,108),5)
u07ch
A: 
SELECT Convert(varchar(5), GetDate(), 108)

Using varchar(5) will automatically truncate the date to remove the seconds.

Keith
+1  A: 

CONVERT(VARCHAR(5),Date, 108)-- Gets only HH:mm

A: 

One way would be to use the RIGHT() function to crop the Date. Something like:

RIGHT(CONVERT(VARCHAR(8),Date, 108),5)

This will only work if number of characters is constant e.g. there is a leading zero if applicable. (Sorry havn't got SQL server here to test).

A better way is to use the T-SQL datepart function to split and then re-concatinate the date parts so:

DARTPART("hh", CONVERT(VARCHAR(8),Date, 108))+":"+DARTPART("mi", CONVERT(VARCHAR(8),Date, 108))

References:
http://msdn.microsoft.com/en-us/library/ms174420.aspx
http://msdn.microsoft.com/en-us/library/ms187928.aspx
http://msdn.microsoft.com/en-us/library/ms177532.aspx

Jona