第二个表" EquipmentStatus" - 它有EquipmentID作为主键,所以它是一个较小的表(这里只有UPDATES),它看起来像这样:
嗯,我需要的是一个新的表,其中车辆可以在Date_1和Date_2之间进行DID通信,即可以提供此的SQL查询:
其中Date_1和Date_2分别设置为20,分别为6月22日)。
此外,下一步是为不能在Date_1和Date_2之间进行通信的车辆(即您在下面看到的车辆)提供一个表格(视图):
感谢您的时间和耐心!
答案 0 :(得分:2)
我在没有数据的情况下对这些进行了攻击,但这应该让你走上正确的道路。
A:
SELECT DISTINCT s.Vehicle_Number, s.Vehicle_Status, s.DateLastCommunication
FROM EquipmentStatus s
INNER JOIN Communications c
ON s.Equipment_ID = c.Equipment_ID
WHERE c.DateTimeCommunication BETWEEN '2015-06-20' AND '2015-06-22'
B:
SELECT DISTINCT s.Vehicle_Number, s.Vehicle_Status, s.DateLastCommunication
FROM EquipmentStatus s
INNER JOIN Communications c
ON s.Equipment_ID = c.Equipment_ID
WHERE s.Equipment_ID NOT IN
(SELECT Equipment_ID FROM Communications WHERE DateTimeCommunication
BETWEEN '2015-06-20' AND '2015-06-22')
答案 1 :(得分:2)
这就是你要找的东西吗?
declare @startDate datetime, @enddate datetime
--vehicles communicated
select A.Vehicle_Number, b.Vehicle_Status, A.DataLastCommunication
from (
Select Vehicle_Number, MAX(DataLastCommunication) as DataLastCommunication
from dbo.Communications
where DataLastCommunication between @startDate and @enddate
group by Vehicle_Number
) as A
inner join dbo.EquipmentStatus b
on a.Vehicle_Number=b.Vehicle_Number
and a.DataLastCommunication = b.DataLastCommunication
--vehicles did not communicate
select a.Vehicle_Number, a.Vehicle_Status, a.DataLastCommunication
from dbo.EquipmentStatus a
where not exists(
select 1
from dbo.Communications
where Vehicle_Number=a.Vehicle_Number
and DataLastCommunication between @startDate and @enddate
)
最后一个查询应该使用车辆表而不是通信表,因为有可能有一辆新车在这两个表中没有任何条目(这将返回车辆号但状态和日期将是null)....
答案 2 :(得分:0)
在sql-server中,您可以使用函数返回两组不同的数据,就像两个新表一样:
create function f_has_comm(@date1 datetime, @date2 datetime)
returns table
as
return (select Vehicle_Number, Vehical_status, DateLastCommunication
from EquipmentStatus where EquipmentID in (select EquipmentID from Communication
where DatetimeCommunication>=@date1 and DatetimeCommunication<=@date2)
)
go
create function f_no_comm(@date1 datetime, @date2 datetime)
returns table
as
return (select Vehicle_Number, Vehical_status, DateLastCommunication
from EquipmentStatus where EquipmentID NOT IN (select EquipmentID from Communication
where DatetimeCommunication>=@date1 and DatetimeCommunication<=@date2)
)
go
现在您可以从以下两个功能中进行选择:
select * from f_has_comm('2015-6-1','2015-6-20');
select * from f_no_comm('2015-6-1','2015-6-20');