Følgende ser ud til at gøre tricket:
SET @locationID=0,@ts=NULL,@changed=0;
SELECT
MIN(assetID) AS id
, MIN(locationID) AS location
, SUM(secDiff) AS duration
FROM
(SELECT
assetID
, locationID
, @changed := IF(locationID <> previousLocationID, @changed + 1, @changed) AS changed
, IFNULL(TIMESTAMPDIFF(SECOND,
previousTs,
ts
),
0
) AS secDiff
FROM
(SELECT
assetID
, locationID
, @locationID AS previousLocationID
, @locationID := locationID AS currentLocationID
, ts
, @ts AS previousTs
, @ts := ts AS currentTs
FROM Logs L1
WHERE assetid = 1157
ORDER BY ts
) L2
ORDER BY ts
) L3
GROUP BY changed
ORDER BY changed DESC
;
Se det i aktion:SQL Fiddle .
Opdatering:
Hvis du har brug for at deltage i yderligere tabeller, bør du faktisk JOIN
og ikke undervalg. Da der er en GROUP BY
på det aktuelt yderste niveau skal den eksisterende erklæring pakkes ind i et andet sæt parenteser - for at forhindre gruppering over faktatabellerne. Med nogle andre justeringer til det formål:
SET @locationID=0,@ts=NULL,@changed=0;
SELECT
A.name
, L4.assetID
, L.name
, L4.locationID
, duration
FROM
(SELECT
MIN(assetID) AS assetID
, MIN(locationID) AS locationID
, SUM(secDiff) AS duration
, changed
FROM
(
-- no change in here
) L3
GROUP BY changed
) L4
JOIN Asset A
ON L4.assetID = A.id
JOIN Location L
ON L4.locationID = L.id
ORDER BY changed DESC
;
Udvidet SQL Fiddle .
Opdatering 2:
Den mest ligetil måde at adressere dubletter på bør være at DISTINCT
dem væk som det allerførste skridt:
-- no change here
(SELECT
assetID
, locationID
, @locationID AS previousLocationID
, @locationID := locationID AS currentLocationID
, ts
, @ts AS previousTs
, @ts := ts AS currentTs
FROM
(SELECT DISTINCT
assetID
, locationID
, ts
FROM Logs
WHERE assetid = 1157
) L1
ORDER BY ts
) L2
-- no change here either
Denne SQL violin returnerer for de duplikerede logfiler data det samme resultatsæt som SQL Fiddle , hvor den tidligere forespørgsel kører mod data uden dubletter.
Kommenter venligst, hvis og da dette kræver justering / yderligere detaljer.