0

Postgresデータベースのテーブルにx、y座標の2つの列があります。

次を使用して、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ステートメントは機能しますが、xminは列ではないことを示しているため、「where」句を使用できません。正しいアプローチは何ですか、または私が正しいアプローチを使用しているという万が一の場合、正しい構文は何ですか?

4

1 に答える 1

3

1つの方法は、結合とサブクエリを使用することです。

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にインデックスがある場合、これらはすべて高速に実行されます。この場合、最後がおそらく最速です。

于 2013-01-23T14:12:43.753 に答える