1

I have this SQL Query, I need to Join my VehicleMonitoring Log Table twice as I need values from Enter and Exit Events where 6 is enter and 7 is Exit.

The Problem is that Enter Time is always the same when I run this script.

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 

Which join is incorrect?

enter image description here

4
  • The join is on iAssetID. It looks like your results show AssetEnter (iAssetId) as the same for all records, so I'd expect the Enter Time to follow suit. Commented Dec 10, 2014 at 17:50
  • looks like your code will list all of the entry and exit times, how do you know that the exit is related the a given entry? Commented Dec 10, 2014 at 17:52
  • I agree with mrtig. You need to define the relationship between the two aliases for vehicleMonitoringLog. Commented Dec 10, 2014 at 17:58
  • An asset can have more than one VehicleMonitoringLog with eEvent 6 or eEvent 7. Commented Dec 10, 2014 at 18:01

1 Answer 1

3

I believe you have a cross product between Assets and the two Vehicle tables.

if you didn't stop at top 100 you'd see after a while Entertime would change and be the same again for a while.

You need to have two asset tables as well as 2 VehiclMontioringLog tables. One for the AssetEnter and one for 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 
Sign up to request clarification or add additional context in comments.

2 Comments

How do I double join the Assets table and VehicleMonitoring talbe?
@DawoodAwan more like this, you need to change the select clause too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.