How to correctly use group by for getting the record with the closest time for each rec_id
WITH cte AS ( SELECT rec_id, 
                     rec_time, 
                     FIRST_VALUE(rec_value) OVER (PARTITION BY rec_id ORDER BY rec_time DESC) rec_value
              FROM records 
              WHERE rec_id IN (4,9,21,565,951,93,6,15,64) 
              AND rec_time &lt;= 590 )
SELECT rec_id, MAX(rec_time) rec_time, rec_value
FROM cte 
GROUP BY rec_id /* , rec_value */ ;


or ever

SELECT DISTINCT rec_id, 
                MAX(rec_time) OVER (PARTITION BY rec_id) rec_time, 
                FIRST_VALUE(rec_value) OVER (PARTITION BY rec_id ORDER BY rec_time DESC) rec_value
FROM records 
WHERE rec_id IN (4,9,21,565,951,93,6,15,64) 
AND rec_time &lt;= 590;