丢失与不同的订单行 - PostgreSQL

时间:2017-08-10 07:41:05

标签: sql postgresql distinct-on

我正在使用SQL,我想用numero_engin if exist else numero_train选择结果。所以我使用coalesce来做这件事。要删除重复的行,我尝试使用distinct。但是使用distinct时出现问题,我失去了行的顺序。

这是我的要求:

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

此请求返回以重复行排序的结果:

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

但是添加distinct时的全局请求会显示无序结果。

1 个答案:

答案 0 :(得分:0)

您需要重新排列

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

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%' 
         ) AS req    
  ORDER BY p.numero_engin, p.utc_horodatage_observation DESC

请注意,我删除了其他ORDER BY

编辑:我注意到您在select distinct中使用*,因此您可能无法获得预期效果。我看不到你的桌子设计 - 但请考虑下面的例子:

表1:

numero_engin | numero_train | something1 | something2
-----------------------------------------------------
engin1       | NULL         | something  | something
engin1       | numero1      | something1 | something2
NULL         | numero1      | something3 | something4

然后你需要一个带有合并的附加列,然后得到:

numero_engin | numero_train | something1 | something2 | coalesce_column
------------------------------------------------------------------------
engin1       | NULL         | something  | something  | engin1
engin1       | numero1      | something1 | something2 | engin1
NULL         | numero1      | something3 | something4 | numero1

到目前为止一切都很好 - 但是现在你想要从coalesce_column获得不同的值 - 但是因为你使用*,那么你实际上说你需要不同的

所以做SELECT DISTINCT coalesce_column FROM TABLE会得到你想要的东西;但是执行SELECT DISTINCT coalesce_column, * FROM TABLE会让您超越表格,因为每行 IS 不同。