我试图每小时从大型SQL DB中提取数据。以下查询给我一个分钟分组。我希望按小时分组数据。
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)
documentation也没有提供任何此类选项。有任何想法吗?
答案 0 :(得分:2)
试试这个,
--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.
答案 1 :(得分:0)
您可以像这样使用子字符串:
select substring(field,1,4) + '-'+ substring(field,6,2) +'-'+ substring(field,7,2)+' '+ substring(field,9,2) from dbo.youtable
答案 2 :(得分:0)
试试这个
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)