2017-06-28 15 views
1

私はGreenplum DBで作業しています。GreenplumのFirst_valueウィンドウ関数

First_valueウィンドウ関数の奇妙な結果を得るには、by節がすべての行に共通の文字列値を渡すと、最初に挿入された行が常に返されますが、理想的には任意のvalue.Belowを返します。

create temporary table test_first_value (id int,statename 
varchar(50),episodeid int, 
episodedate date) distributed by (id); 

insert into test_first_value values(12,'MP',9863,'2015-11-06'); 
insert into test_first_value values(12,'MP',98123,'2009-11-06'); 
insert into test_first_value values(12,'MP',90123,'2017-03-06'); 
insert into test_first_value values(12,'MP',44567,'2013-03-17'); 
insert into test_first_value values(13,'MP',189300,'2013-03-17'); 
insert into test_first_value values(13,'MP',443467,'2016-03-19'); 

それは常に最初に挿入されたのと同じ値を返すされていることであるepisodeid = 9863 ID = 13

Select *, 
First_value(episodeid) over(partition by id order by statename) as 
first_episodeid, 
First_value(episodedate) over(partition by id order by statename) as 
first_episodedate 
from 
test_first_value; 

enter image description here

用ID = 12とepisodeid = 189300のために

は今、次に私の挿入順序を変更する場合は、常に最初に挿入された行の値を返すようにepisodeid = 98123、ID = 12とepisodeidのID = 13

delete from test_first_value; 

insert into test_first_value values(12,'MP',98123,'2009-11-06'); 
insert into test_first_value values(12,'MP',90123,'2017-03-06'); 
insert into test_first_value values(12,'MP',44567,'2013-03-17'); 
insert into test_first_value values(12,'MP',9863,'2015-11-06'); 
insert into test_first_value values(13,'MP',443467,'2016-03-19'); 
insert into test_first_value values(13,'MP',189300,'2013-03-17'); 

Select *, 
First_value(episodeid) over(partition by id order by statename) as 
first_episodeid, 
First_value(episodedate) over(partition by id order by statename) as 
first_episodedate 
from 
test_first_value; 

enter image description here

ため= 443467であります

私が間違っているところで助けてください。

+0

質問を編集し、「奇妙な結果」を表示してください。また、あなたが得たい結果を説明する必要があります。 –

+0

私は 'id by partition、episodedateでのstatename order'が必要かもしれないと思う。 –

+0

@Praあなたは順序通りにstatenameだけを使う。あなたはこの場合にあなたが持つことを予測することはできません。 –

答えて

0

コードは正常に動作します。あなた自身がデータで示しているように、あなたは同じstatenameidための複数の行を持つ

First_value(episodeid) over(partition by id order by statename) 

:これはあなたの窓関数です。この状況では、データベースは一致するキーから任意の不確定な値を返します。

これを言う別の方法は、ソートがリレーショナルデータベースでは安定していないことです。理由は簡単です:テーブルは、の順番を並べていませんセットを表します。ソートキーがすべて同じ場合、代わりに使用する自然順序付けはありません。

したがって、が別のキーを見つけて、各行を一意に識別できるようにします。つまり、目的の行が一意に識別されるため、結果は安定します。あなたのデータでは、order byに第2の鍵としてepisode_dateを追加することができます。

関連する問題