双内连接 - 不正确的结果

时间:2014-12-10 17:45:26

标签: sql sql-server join

我有这个SQL查询,我需要加入我的VehicleMonitoring Log Table两次,因为我需要输入和退出事件的值,其中6是输入,7是退出。

问题是,当我运行此脚本时,输入时间始终相同。

Select top 100
    aEnter.iAssetId as AssetEnter, 
    aEnter.iAssetId as AssetExit, 
    vmEnter.dtUTCDateTime,
    g.iGeofenceId,
    g.sGeofenceName,
    c.sCategoryName,
    c.iCategoryId,
    s.sSiteName,
    s.iSiteId,
    vmEnter.dtUTCDateTime as EnterTime,
    vmExit.dtUTCDateTime as ExitTime
    --,
    --convert(char(8),dateadd(s,DATEDIFF(s,vmEnter.dtUTCDateTime, vmExit.dtUTCDateTime ),'1900-1-1'),8) as Times
From Sites s
    Inner Join Categories c on s.iSiteId = c.iSiteId
    Inner Join Assets aEnter on c.iCategoryId =  aEnter.iCategoryId
    Inner Join VehicleMonitoringLog vmEnter on vmEnter.iAssetId = aEnter.iAssetId and vmEnter.eEventCode = 6
    Inner Join VehicleMonitoringLog vmExit on vmExit.iAssetId = aEnter.iAssetId and vmExit.eEventCode = 7
    Inner Join Geofences g on g.iGeofenceId = vmEnter.iGeofenceId

哪个加入不正确?

enter image description here

1 个答案:

答案 0 :(得分:3)

我相信你在Assets和两个Vehicle表之间有一个交叉产品。

如果你没有停在前100名,你会看到一段时间后,Entertime会改变,并且暂时再次相同。

您需要拥有两个资产表以及2个VehiclMontioringLog表。一个用于AssetEnter,一个用于AssetExit。

Select top 100
aEnter.iAssetId as AssetEnter, 
aExit.iAssetId as AssetExit, 
vmEnter.dtUTCDateTime,
g.iGeofenceId

From Sites s
Inner Join Categories c on s.iSiteId = c.iSiteId
Inner Join Assets eEnter on c.iCategoryId =  aEnter.iCategoryId
Inner Join Assets aExit on c.iCategoryId =  aExit.iCategoryId
Inner Join VehicleMonitoringLog vmEnter on vmEnter.iAssetId = aEnter.iAssetId and vmEnter.eEventCode = 6
Inner Join VehicleMonitoringLog vmExit on vmExit.iAssetId = aExit.iAssetId and vmExit.eEventCode = 7
Inner Join Geofences g on g.iGeofenceId = vmEnter.iGeofenceId