I'm working with SQL
and i want to select result with numero_engin if exist else numero_train
. So i'm using coalesce
to do this. To romove the duplicate rows, i tried to use distinct
. But the problem when using distinct
, i lose the order of rows.
Here is my request :
SELECT DISTINCT on (req.cle) req.cle,*
FROM (SELECT coalesce(p.numero_engin, p.numero_train) AS cle, *
FROM last_position p
WHERE 1=1
AND p.source_localisation LIKE 'B%'
ORDER BY p.numero_engin, p.utc_horodatage_observation DESC) AS req
ORDER BY req.cle,req.utc_horodatage_observation DESC
This request return the result ordered with the duplicate rows :
SELECT COALESCE(p.numero_engin, p.numero_train) AS cle, *
FROM last_position p
WHERE 1=1
AND p.source_localisation LIKE 'B%'
ORDER BY p.numero_engin, p.utc_horodatage_observation DESC
But the global request when adding distinct
, display a disordered result.