2013-01-23 24 views
0

我在Postgres數據庫的表格中有兩列x,y座標。在postgresSQL中查找最大值/最小值對

我可以找到使用在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億行數據集中的四個極值點? (練習的要點)

所需的select語句有效,但我不能使用「where」子句,因爲它表示xmin不是列。什麼是正確的方法,或者在不太可能的情況下,我正在使用正確的方法,請問什麼是正確的語法?

回答

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上有索引,這些將會運行得更快。在這種情況下,最後一個可能是最快的。

+0

你明白了:D所以不妨投票你=) – bonCodigo

+0

最快是最快的 - 每聲明600-640毫秒。 – DHBI

相關問題