按照IN子句的顺序查询数据

1 sql postgresql group-by having

select osmid,ST_X(shape),ST_Y(shape) 
from osmpoints 
where (osmpoints.osmid, osmpoints.osmtimestamp) 
     IN  (select osmid,MAX(osmtimestamp) 
          from osmPoints 
          GROUP BY osmid 
          Having MAX(osmtimestamp) <= '2019-09-16T01:23:55Z' 
            AND osmid in ('4426786454','1861591896','1861591869','1861591895',
                          '4426786455','2038185115','1861591853','6797739995',
                          '2299605892','6797739994','1861591898','2038185111','4426786454'));
Run Code Online (Sandbox Code Playgroud)

当我运行这个查询时,我得到基于 osmid 列的排序行。但我的问题是如何按在 IN 子句中使用的 osmid 的顺序获取行?

a_h*_*ame 5

您可以使用与此处所示相同的技术:

with input(idlist) as (
  values (
    array['4426786454','1861591896','1861591869','1861591895',
         '4426786455','2038185115','1861591853','6797739995',
         '2299605892','6797739994','1861591898','2038185111','4426786454']::text[])
)
select p.osmid,ST_X(shape),ST_Y(shape) 
from osmpoints p
 cross join input
where (p.osmid, p.osmtimestamp) IN  (select osmid,MAX(osmtimestamp) 
                                     from osmPoints
                                        cross join input
                                     GROUP BY osmid 
                                     Having MAX(osmtimestamp) <= '2019-09-16T01:23:55Z' 
                                        AND osmid = any(idlist))
order by array_position(idlist, osmid);
Run Code Online (Sandbox Code Playgroud)