【发布时间】:2020-12-17 10:35:51
【问题描述】:
我有多个设备 IMEI,它们会连续发送数据。有一个表格可以查看设备发送最后一个数据的时间,格式如下:12/17/2020 4:05:02 PM。现在我想获取那些在过去 4 个月内发送数据的设备。我得到了连接,但无法理解我需要在 Where 子句中设置的条件。
【问题讨论】:
标签: sql sql-server datetime where-clause
我有多个设备 IMEI,它们会连续发送数据。有一个表格可以查看设备发送最后一个数据的时间,格式如下:12/17/2020 4:05:02 PM。现在我想获取那些在过去 4 个月内发送数据的设备。我得到了连接,但无法理解我需要在 Where 子句中设置的条件。
【问题讨论】:
标签: sql sql-server datetime where-clause
SQL Server 在将字符串转换为日期方面非常灵活,因此您应该能够只使用convert() 或cast(),并进行直接过滤。
所以:
where convert(datetime, mycol) >= dateadd(month, -4, getdate())
这会过滤过去 4 个月的数据,从当前日期/时间开始。如果您想要整个月份(当前月份和前三个月)
where convert(datetime, mycol) >= dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1)
【讨论】:
现在我想获取那些在过去 4 个月内发送过数据的设备。
这听起来像exists。如果您的意思是 4 个月到一天 并且 datetime 列正确存储为 datetime,那么:
select d.*
from devices d
where exists (select 1
from table2 t2
where t2.imei = t.imei and
t2.datetime >= dateadd(month, -4, getdate())
);
如果您指的是当前日历月或前三个日历月,那么:
select d.*
from devices d
where exists (select 1
from table2 t2
where t2.imei = t.imei and
t2.datetime >= dateadd(month, -3, datefromparts(year(getdate(), month(getdate()), 1))
);
如果“日期时间”列存储为字符串,则修复数据。在表中使用正确的类型。您可以转换为datetime,因为 SQL Server 会识别格式:
select d.*
from devices d
where exists (select 1
from table2 t2
where t2.imei = t.imei and
try_convert(datetime, t2.datetime) >= dateadd(month, -4, getdate())
);
但是,您应该使用正确的数据库类型来存储这些值。
【讨论】: