sql - 使用 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 本身中做减法不太熟悉。我还应该添加什么来解决这个问题吗?
解决方案
上存在语法错误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]
推荐阅读
- c# - 如何在 owasp zap 中单独扫描特定的 URL 或页面
- linux - 每次添加新用户时如何运行特定命令
- c# - WPF TextBox 数据绑定,仅部分工作
- javascript - 如何在不更改 Javascript 的情况下打开 ul 时添加样式:inline-block?
- google-cloud-platform - 为什么它提供 2 com.google.cloud/services/compute-engine/VmimageN1StandardCore 测量?我只有一个实例在运行
- javascript - 如何为动态生成的表编写实时搜索功能?
- r - 如何对矩阵进行转换和排序以制作显示签名的热图?
- firebase - 如何在 Expo Firebase 中向特定用户发送推送通知
- postgresql - 尝试通过 ssh 与酒保连接时返回代码 255
- python - Mailgun 内联图像 utf-8 png