我真的需要Database ninjas的帮助。
我有以下代码:
SELECT DATEPART(hh, BeginMinute) AS Intervalo, SUM(Qtde) AS Total
FROM tr_CustomerCount
WHERE BeginMinute > '5/22/2013 00:00:00 AM' AND BeginMinute < '6/22/2013 12:00:00 AM'
GROUP BY DATEPART(hh, BeginMinute)
实际上它只返回小时(HH),但我想把“HOUR”和“MINUTE”一起显示为“:”这样的'12:00'它可以是一个字符串,不用担心。
我该怎么做?
提前致谢!
答案 0 :(得分:14)
您可以将CONVERT与样式114(Date and Time Styles
}部分一起使用:
SELECT CONVERT(VARCHAR(5), GETDATE(), 114);
或者,从SQL Server 2012开始,您可以使用FORMAT(demo):
SELECT FORMAT(GETDATE() , 'hh:mm');
答案 1 :(得分:1)
示例:
DECLARE @theDate DATETIME
SET @theDate = CURRENT_TIMESTAMP
SELECT @theDate
PRINT (RIGHT('00' + convert(varchar(2), DATEPART(hour, @theDate)), 2) +
':' + RIGHT('00' + convert(varchar(2), DATEPART(minute, @theDate)), 2))
说明:
'string 1' + 'string 2'
答案 2 :(得分:1)
SELECT RIGHT('00' + rtrim(cast(DATEPART(hh, BeginMinute) as varchar)), 2) + ':' +
RIGHT('00' + rtrim(cast(DATEPART(mi, BeginMinute) as varchar)), 2) AS Intervalo,
SUM(Qtde) AS Total
FROM tr_CustomerCount
WHERE BeginMinute > '5/22/2013 00:00:00 AM'
AND BeginMinute < '6/22/2013 12:00:00 AM'
GROUP BY DATEPART(hh, BeginMinute), DATEPART(mi, BeginMinute)
答案 3 :(得分:1)
这对于一些微不足道的事情来说非常复杂。你为什么不试试:
left(convert(varchar,current_timestamp,108),5)
将日期时间值转换为24小时制的小时和分钟字符串表示,因此,比如2:37 PM的时间将转换为字符串值14:37
。
一旦你拥有了,那么......
select time_hhmm = left(convert(varchar,BeginMinute,108),5) ,
total = sum(Qtde)
from tr_CustomerCount
where BeginMinute > '5/22/2013 00:00:00 AM'
and BeginMinute < '6/22/2013 12:00:00 AM'
group by left(convert(varchar,BeginMinute,108),5)
眼睛容易多了。
修改后反映每个OP的评论只显示HH:00:
select time_hhmm = right( '0'+datename(hour,BeginMinute) , 2 ) + ':00 ,
total = sum(Qtde)
from tr_CustomerCount
where BeginMinute > '5/22/2013 00:00:00 AM'
and BeginMinute < '6/22/2013 12:00:00 AM'
group by datename(hour,BeginMinute)