如何在SQL Server中将时间从09:00:00.0000000格式化为9:00?

时间:2019-11-06 11:02:06

标签: sql sql-server

我写了以下查询:

SELECT CASE WHEN rpwh.StartDayOfTheWeek = 1 THEN 7
WHEN rpwh.StartDayOfTheWeek = 2 THEN 1 
WHEN rpwh.StartDayOfTheWeek = 3 THEN 2 
WHEN rpwh.StartDayOfTheWeek = 4 THEN 3 
WHEN rpwh.StartDayOfTheWeek = 5 THEN 4 
WHEN rpwh.StartDayOfTheWeek = 6 THEN 5 
WHEN rpwh.StartDayOfTheWeek = 7 THEN 6
END AS StartDayOfTheWeek,
DATENAME(WEEKDAY, rpwh.StartDayOfTheWeek - 2) DayOfTheWeek,
rpwh.StartAt, rpwh.EndAt
FROM ResourceProfileWorkingHours rpwh
JOIN ResourceProfile rp ON rpwh.ResourceProfileId = rp.Id
WHERE rp.Alias = 'Accounts Payable'
ORDER BY StartDayOfTheWeek

哪个返回:

StartDayOfTheWeek   DayOfTheWeek    StartAt              EndAt
1                   Monday          09:00:00.0000000     17:00:00.0000000
2                   Tuesday         09:00:00.0000000     17:00:00.0000000
3                   Wednesday       09:00:00.0000000     17:00:00.0000000
4                   Thursday        09:00:00.0000000     17:00:00.0000000
5                   Friday          09:00:00.0000000     17:00:00.0000000
6                   Saturday        09:00:00.0000000     17:00:00.0000000
7                   Sunday          09:00:00.0000000     17:00:00.0000000

我需要将StartAt时间转换为9:00,将EndAt时间转换为17:00。我尝试编写下面的行,但是当我运行它时,两列的值都为空。我该怎么办?

FORMAT(rpwh.StartAt,'hh:mm') AS StartTime, FORMAT(rpwh.EndAt, 'hh:mm') AS EndTime

3 个答案:

答案 0 :(得分:0)

我使用了@droebi的建议:

SELECT CONVERT (VARCHAR (5), <YourTimeCol>, 108)

这不是一个完美的解决方案,因为它的开始时间仍然是09:00,而不是9:00,但这是我能最接近自己想要的时间

答案 1 :(得分:0)

这有效:

network_mode: "host"

我将时间格式化为日期,然后仅选择时间。

答案 2 :(得分:-2)

如果您不担心丢失数据类型,可以随时使用:

LEFT(CAST(StartAt, AS STRING), 5)