首页 > 解决方案 > 使用 12 小时表示法格式化时间

问题描述

我做了一个显示日期和时间的 SQL 查询,时间分为小时和分钟。

select convert(varchar(10),[Date],23) as [Date], 
datepart(hour, [Time])as Hour, datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

该表以 24 小时格式显示小时。但我想改为 12 小时格式,单个数字带有“0”前缀。

即:01、02、03等。

我想用案例来做到这一点:

select convert(varchar(10),[Date],23) as [Date],
case when 
datepart(hour, [Time])> 12 then (datepart(hour, [Time])- 12) as Hour
, datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

这样做会给我在线语法错误

datepart(hour, [Time])> 12 then (datepart(hour, [Time])- 12) as Hour

--Incorrect syntax near the keyword 'as'.

我对在 SQL 本身中做减法不太熟悉。我还应该添加什么来解决这个问题吗?

标签: sqlsql-serversql-server-2008

解决方案


上存在语法错误case when,请尝试以下操作。

select convert(varchar(10),[Date],23) as [Date]
    , case when datepart(hour, [Time])> 12
    then (datepart(hour, [Time])- 12) 
    else datepart(hour, [Time]) End as Hour
    , datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

推荐阅读