WITH work_orders_with_status AS (
  SELECT id, work_orders.location_id, scheduled_date, expiration_date, extended_status_code
  FROM work_orders JOIN work_order_statuses ON id = work_order_id
  WHERE deleted IS NOT TRUE AND (NOW() at time zone 'utc') BETWEEN (scheduled_date - ('24 hours')::interval) AND  (expiration_date + ('24 hours')::interval)
 )

SELECT MIN(ws2.id) AS work_order_id, temp.location_id , MIN(temp.status) AS status_code
FROM 
  (
    SELECT
      ws1.location_id,
      MIN(ws1.extended_status_code) AS status
    FROM work_orders_with_status ws1
    GROUP BY ws1.location_id
  ) temp
  JOIN work_orders_with_status ws2 ON temp.location_id = ws2.location_id AND temp.status = ws2.extended_status_code
GROUP BY temp.location_id
