query update

This commit is contained in:
Pringgosutono
2025-09-22 15:24:26 +07:00
parent e1153c375d
commit 65f7cc1ebf

View File

@ -59,15 +59,15 @@ class ReportsController extends Controller
// $to_date = 1756745940;
try {
$list = DB::select("WITH trips AS (
$list = DB::select("WITH
gaps AS (
SELECT
t.*,
-- mark the start of a trip when ignition=4 and previous ignition <> 4
-- previous gap since previous row > 1 hour (3600s)
CASE
WHEN ignition = 4
AND LAG(ignition, 1, 0) OVER (PARTITION BY vhc_id ORDER BY crt_d) <> 4
WHEN (crt_d - LAG(crt_d, 1, NULL) OVER (PARTITION BY vhc_id ORDER BY crt_d)) > 3600
THEN 1 ELSE 0
END AS trip_start
END AS isStop,
t.*
FROM t_gps_tracks t
WHERE
t.latitude IS NOT NULL
@ -75,13 +75,27 @@ class ReportsController extends Controller
AND t.action = 'location'
AND t.crt_d BETWEEN ? AND ?
)
, trips AS (
SELECT
-- mark the start of a trip when ignition=4 and previous ignition <> 4
CASE
WHEN ignition = 4
AND LAG(ignition, 1, 0) OVER (PARTITION BY vhc_id ORDER BY crt_d) <> 4
or LAG(isStop, 1, 0) over (PARTITION BY vhc_id ORDER BY crt_d) = 1
THEN 1 ELSE 0
END AS trip_start,
g.*
FROM gaps g
)
, numbered AS (
SELECT
*,
-- assign a trip_id by cumulative sum of trip_start
SUM(trip_start) OVER (PARTITION BY vhc_id ORDER BY crt_d) AS trip_id
FROM trips
where ignition = 4
where
ignition = 4
and isStop = 0
),
agg AS (
SELECT