I have the following query that is returning the expected results:
SELECT
locations.*,
(
SELECT
id
FROM
hauls
WHERE
haul_type_id = 1
AND location_id = locations.id
ORDER BY
created_at DESC
LIMIT 1) AS last_delivery_id,
(
SELECT
id
FROM
hauls
WHERE
haul_type_id = 2
AND location_id = locations.id
ORDER BY
created_at DESC
LIMIT 1) AS last_pickup_id
FROM
locations
I would like to use the results of the subqueries (last_delivery_id
, last_pickup_id
) in a case statement in the parent query but I'm getting an error :
ERROR: Unknown column 'last_delivery_id'
SELECT
locations.*,
case when last_delivery_id = 1 then 'pending' when last_delivery_id = 2 then 'active' end as status,
(
SELECT
id
FROM
hauls
WHERE
haul_type_id = 1
AND location_id = locations.id
ORDER BY
created_at DESC
LIMIT 1) AS last_delivery_id,
(
SELECT
id
FROM
hauls
WHERE
haul_type_id = 2
AND location_id = locations.id
ORDER BY
created_at DESC
LIMIT 1) AS last_pickup_id
FROM
locations