我有一個觀點具有SQL腳本:合併兩行條件SQL視圖
Select
a.iAssetId,
ac.eEventCode,
vm.dtUTCDateTime,
g.iGeofenceId,
g.sGeofenceName,
c.sCategoryName,
c.iCategoryId,
s.sSiteName,
s.iSiteId,
CASE WHEN ac.eEventCode = 6 THEN vm.dtUTCDateTime ELSE NULL END as EnterTime,
CASE WHEN ac.eEventCode = 7 THEN vm.dtUTCDateTime ELSE NULL END as ExitTime,
CASE WHEN
a.iAssetId = Lead(a.iAssetId) OVER (ORDER BY a.iAssetId)
AND g.iGeofenceId = Lead(g.iGeofenceId) OVER (ORDER BY a.iAssetId)
AND ac.eEventCode != Lead(ac.eEventCode) OVER (ORDER BY a.iAssetId)
THEN DATEDIFF(minute, vm.dtUTCDateTime, Lead(vm.dtUTCDateTime) OVER (ORDER BY a.iAssetId)) ELSE NULL END as Test
From AssetCommunicationSummary ac
Inner join VehicleMonitoringLog vm on vm.iVehicleMonitoringId = ac.iVehicleMonitoringId
Inner Join Geofences g on g.iGeofenceId = vm.iGeofenceId
Inner Join Assets a on a.iAssetId = ac.iAssetId
Inner Join Categories c on c.iCategoryId = a.iCategoryId
Inner Join Sites s on s.iSiteId = c.iSiteId
Where ac.eEventCode = 6 OR ac.eEventCode = 7
Group by
a.iAssetId,
ac.eEventCode,
vm.dtUTCDateTime,
g.iGeofenceId,
g.sGeofenceName,
c.sCategoryName,
c.iCategoryId,
s.sSiteName,
s.iSiteId
我用鉛來計算分鐘,領先的基於條件的行時間differenc。
我需要現在基於條件合併領先的行和當前行。
有沒有可能的方法來做到這一點?
目標是讓EnterTime和ExitTime在列旁邊的同一行中添加時間差。
我的結果是這樣的:
在'MAX()'函數中放置列'EnterTime','ExitTime'和'Test',並由其餘列組成列。 – 2014-11-14 23:30:40
這個的任何例子?我必須合併AssetId相同的roes,geofence是相同的,事件是6和7. – 2014-11-14 23:36:50
您是否必須在結果中實際顯示事件代碼?事件代碼似乎已經進入和退出時間已經隱含。如果您不必在結果中顯示事件代碼,則只要您將其從組中移除並選擇,就會看到您的查詢已經做到了您想要的。 – Daileyo 2014-11-17 19:35:14