我在Postgres数据库的表中有两列x,y坐标。
我可以使用:
找到x和y中的极值select min(x), max(x), min(y), max(y)
from coords
如何将这些变量分配给这样的变量:
select min(x) as xmin, max(x) as xmax, min(y) as ymin, max(y) as ymax
from coords
实现
select y
from coords
where x = xmin
等...获取5亿行数据集中的4个极值点? (演习的重点)
所需的select语句有效,但我不能使用“where”子句,因为它表示xmin不是列。什么是正确的方法,或者在我使用正确方法的情况下,正确的语法是什么?
答案 0 :(得分:3)
一种方法是使用连接和子查询:
select c.*
from coords c join
(select min(x) as xmin, max(x) as xmax, min(y) as ymin, max(y) as ymax
from coords
) clim
on c.x in (clim.xmin, clim.xmax) or c.y in (clim.ymin, clim.ymax)
另一种方法是使用窗口函数:
select c.*
from (select c.*,
least(row_number() over (order by x),
row_number() over (order by x desc),
row_number() over (order by y),
row_number() over (order by y desc)
) as seqnum
from coords c
) c
where seqnum = 1
另一方面,如果你真的只想要4分就是:
select * from coords order by x limit 1 union all
select * from coords order by x desc limit 1 union all
select * from coords order by y limit 1 union all
select * from coords order by y desc limit 1
如果有大量的行,如果你有x和y的索引,它们都会运行得更快。在这种情况下,最后一个可能是最快的。