I have a hauls table that has columns id location_id completed_at and others. I would like to add a column to the query results that has the days since the previous completed haul. This query returns the expected results:
SELECT
`h`.*,
(
SELECT
`completed_at`
FROM
`hauls`
WHERE
`location_id` = `h`.`location_id`
AND `completed_at` < `h`.`completed_at`
ORDER BY
`completed_at` DESC
LIMIT 1) AS `previous_completed_at`
FROM
hauls h
But I would like to use DATEDIFF(h.completed_at, previous_completed_at) as days in the parent query select statement but previous_completed_at cannot be found.
I realize I could use a lateral join but I need this to be MySQL 5.7 compatible.
Is there a way to accomplish this?
LAG()function. – ypercubeᵀᴹ Sep 01 '21 at 12:13