[pgsql-jp: 31176] Re: 複数の入力それぞれの最新の値を求めるSQL 文
gotou
gotou @ hokkou.co.jp
2003年 10月 6日 (月) 17:13:29 JST
ごとうです。
間違えました。
>
> ごとうです。
>
> >
> > こんにちは。SQL文でいい方法が思いつかず質問です。
> >
> > 端末が複数あり、それぞれの端末には番号が振ってあるとします。
> > DBには、どの端末から、いつ、どんな値が入力されたかを記録する
> > ものとします。
> >
> > create table test_tbl {
> > termid int4 ;端末番号
> > , dt datetime ;入力時間
> > , val int4 ;入力データ
> > };
> >
> > ここから、それぞれの端末の最新データを取りたいと考えました。
> > 思いついたのは次の2つ
> > 1:入力されるたびに端末ごとの最新のデータだけを保持する
> > 別のテーブル(またはファイル)を用意する
> > 2:Viewを作って対処
> > create view test_view (termid, dtmax)
> > as select termid, max(dt) as dtmax from test_tbl
> > group by termid;
> > 取り出すときは
> > select * from test_tbl as tt, test_view as tv
> > where tt.termid=tv.termid AND tt.dt=tv.dtmax;
> >
> > ということで解決しているといえば解決しているのですが、
> > 何かもっと簡単に書けるのではないかと思い、MLに投げさせて
> > もらいました。
> > いい方法がありましたらアドバイスください。
> >
> >
> > --
> > __________
> > (_ _______()
> > __||_[]_||__
> > (___________()
> > ||‡‡|| 鳥居 大哉 (Hiroya TORII)
> > || ||
> > ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
> >
> >
>
> inner文ではいけませんか?
>
> select termid, t1.val from test_tbl as t1 inner join
> (select termid, max(dt)as dt from test_tbl group by termid)as t2
> using (termid, dt)
>
select termid, t1.val from test_tbl as t1 inner join
(select termid, max(dt)as dt from test_tbl group by termid)as t2
using (termid, dt)
group by termid;
とかしないと、inner文の意味ないですね。おそらく。
ごめんなさい。
頭の中だけで書いているので、正確なSQLがかけてないかもしれませんが。
余計な混乱を招いていないことを願います。
pgsql-jp メーリングリストの案内