query data in the order of IN clause

痴心易碎 提交于 2021-02-11 06:12:53

问题


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'));

when I run this query, I get sorted rows based on osmid column. but my question is how can I get rows in order of osmid that use in the IN clause?


回答1:


You can use the same technique as shown here:

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);


来源:https://stackoverflow.com/questions/59964580/query-data-in-the-order-of-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!