我正在尝试根据日期和时间获取最新记录,但列包含的时间是12小时AM / PM格式。
假设我的记录在
2015-09-07 12:50:37.1983315 PM - 来这个记录
2015-09-07 03:12:15.1983315 PM - 实际上我需要获得此记录。
以上结果来自以下查询..
SELECT top 10 * FROM SHAdminMessageIndex where Appid='62001308607984608300' and
PolicyNumber='0081317' order by BeginTime desc
那么如何通过AM和PM使用12小时格式来获得结果。在此先感谢
答案 0 :(得分:0)
试试这个
SELECT top 10 * FROM SHAdminMessageIndex where Appid='62001308607984608300'
and PolicyNumber='0081317' order by stuff(convert(varchar(19), BeginTime,
126),11,1,' ') desc
答案 1 :(得分:0)
试试这个
SELECT top 10 * FROM SHAdminMessageIndex
where Appid='62001308607984608300' and PolicyNumber='0081317'
order by
cast(BeginTime as datetime2) desc
OR
SELECT top 10 * FROM SHAdminMessageIndex
where Appid='62001308607984608300' and PolicyNumber='0081317'
order by
cast(left(BeginTime,charindex('.',BeginTime)-1)+right(BeginTime,2) as datetime) desc
答案 2 :(得分:0)
你想要每天的第一张唱片吗?您可以按日期分组并获取每个组的第一个。因此,请使用排名函数,例如ROW_NUMBER
和CTE
:
WITH CTE AS
(
SELECT t.*,
RN = ROW_NUMBER() OVER (PARTITION BY CAST(BeginTime AS Date) ORDER BY BeginTime )
FROM SHAdminMessageIndex t
WHERE Appid='62001308607984608300'
AND PolicyNumber='0081317'
)
SELECT TOP 10 CTE.*
FROM CTE
WHERE RN = 1
ORDER BY BeginTime DESC
答案 3 :(得分:0)
这就是我们应该始终使用正确的数据类型来存储数据的原因。尝试将BeginTime
投射到DATETIME2
SELECT top 10 *
FROM SHAdminMessageIndex
where Appid='62001308607984608300'
and PolicyNumber='0081317'
order by Cast(BeginTime AS DATETIME2) DESC
答案 4 :(得分:0)
使用PARSE将字符串转换为DATETIME2。
select top 10 *
from SHAdminMessageIndex
where Appid='62001308607984608300' and PolicyNumber='0081317'
order by parse(BeginTime as datetime2 using 'en-US') desc;
确保指定语言,例如不依赖于会话设置 - 您的日期时间字符串可能不是另一种语言的有效日期时间(在许多语言中PM和AM无效)。