3

Windows Server 2008 R2 で PostGIS 2.0.3 を使用して PostgreSQL 9.1.9 x64 を実行しています。

私はテーブルを持っています:

CREATE TABLE field_data.trench_samples (
   pgid SERIAL NOT NULL,
   trench_id TEXT,
   sample_id TEXT,
   from_m INTEGER
);

その中にいくつかのデータがあります:

INSERT INTO field_data.trench_samples (
   trench_id, sample_id, from_m
)
VALUES
   ('TR01', '1000001', 0),
   ('TR01', '1000002', 5),
   ('TR01', '1000003', 10),
   ('TR01', '1000004', 15),
   ('TR02', '1000005', 0),
   ('TR02', '1000006', 3),
   ('TR02', '1000007', 9),
   ('TR02', '1000008', 14);

今、私が興味を持っているのは、レコードの「from_m」とそのtrench_idの「次の」「from_m」の違い(この例ではメートル単位の距離)を見つけることです。

したがって、上記のデータに基づいて、次のテーブルを生成するクエリを作成したいと思います。

pgid, trench_id, sample_id, from_m, to_m, interval
1, 'TR01', '1000001', 0, 5, 5
2, 'TR01', '1000002', 5, 10, 5
3, 'TR01', '1000003', 10, 15, 5
4, 'TR01', '1000004', 15, 20, 5
5, 'TR02', '1000005', 0, 3, 3
6, 'TR02', '1000006', 3, 9, 6
7, 'TR02', '1000007', 9, 14, 5
8, 'TR02', '1000008', 14, 19, 5

ここで、「待ってください。比較する「次の」from_m がないので、各行の最後のサンプルの間隔の長さをどのように推測するのですか?」と言っている可能性があります。

行の「端」(sample_id 1000004 と 1000008) には、前の 2 つのサンプルと同じ間隔の長さを使用したいと思います。

もちろん、現在の環境でこれに取り組む方法はわかりません。よろしくお願いいたします。

4

1 に答える 1

1

Here is how you get the difference, using the one previous example at the end (as shown in the data but not explained clearly in the text).

The logic here is repeated application of lead() and lag(). First apply lead() to calculate the interval. Then apply lag() to calculate the interval at the boundary, by using the previous interval.

The rest is basically just arithmetic:

select trench_id, sample_id, from_m,
       coalesce(to_m,
                from_m + lag(interval) over (partition by trench_id order by sample_id)
               ) as to_m,
       coalesce(interval, lag(interval) over (partition by trench_id order by sample_id))
from (select t.*,
             lead(from_m) over (partition by trench_id order by sample_id) as to_m,
             (lead(from_m) over (partition by trench_id order by sample_id) -
              from_m
             ) as interval
      from field_data.trench_samples t
     ) t

Here is the SQLFiddle showing it working.

于 2013-07-07T19:25:31.463 に答える