简体   繁体   中英

CONVERT Time from {yyyy-mm-dd hh:mm:ss} to {yyyy-mm-dd hh}

I am trying to extract data from a large SQL DB on hourly basis. The following query is giving me a grouping on minute basis. I wish to group by the data on hourly basis.

select CONVERT(VARCHAR(20), t.counterTime, 100) as [Time],
    t.instanceName
from table as t
WHERE t.counterId= @counterId
and t.counterTime >=  @startTime
and t.counterTime <  @endTime
group by t.instanceName, CONVERT(VARCHAR(20), t.counterTime, 100)

The documentation also does not provide any such option. Any ideas?

Try like this,

--SQL Server 2012
SELECT FORMAT(t.counterTime, 'yyyy-MM-dd HH') AS [Time]
    ,t.instanceName
FROM TABLE AS t
WHERE t.counterId = @counterId
    AND t.counterTime >= @startTime
    AND t.counterTime < @endTime
GROUP BY t.instanceName
    ,FORMAT(t.counterTime, 'yyyy-MM-dd HH')

--for earlier versions
SELECT CONVERT(CHAR(13), t.counterTime, 120) AS [Time]
    ,t.instanceName
FROM TABLE AS t
WHERE t.counterId = @counterId
    AND t.counterTime >= @startTime
    AND t.counterTime < @endTime
GROUP BY t.instanceName
    ,CONVERT(CHAR(13), t.counterTime, 120)

Note: Format would be perfoming slower.

您可以使用以下子字符串:

select substring(field,1,4) + '-'+ substring(field,6,2) +'-'+ substring(field,7,2)+' '+ substring(field,9,2)  from dbo.youtable 

Try this

select datepart(hour,t.counterTime) as [Time],
    t.instanceName
from table as t
WHERE t.counterId= @counterId
and t.counterTime >=  @startTime
and t.counterTime <  @endTime
group by t.instanceName, datepart(hour,t.counterTime) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM