2016-08-30 20 views
0

でグループを使用して、私は、次の表を持っている:インパラ:基準に選択フィールド

id | animal | timestamp | team 
--------------------------------------- 
1 | dog  | 2016-08-01 | blue 
2 | cat  | 2016-08-02 | blue 
3 | bird  | 2016-07-05 | red 
4 | cow  | 2016-08-04 | red 
5 | snake  | 2016-08-12 | yellow 

私が基準にチームごとに動物を見つけたいこと:チームは、複数の動物を持っている場合、我々後のタイムスタンプを持つものを選択します。これは可能ですか?ありがとう!

答えて

1

典型的なアプローチはrow_number()を使用しています。

select t.* 
from (select t.*, 
      row_number() over (partition by team order by timestamp desc) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
0

あなたは例えば次のクエリを使用できます。実際には

select * from teams t1 where `timestamp`=(select min(t2.`timestamp`) from teams t2 where t2.team = t1.team); 

を:

[localhost:21000] > create table teams(id int, animal string, `timestamp` timestamp, team string); 
[localhost:21000] > insert into teams values (1, "dog", "2016-08-01", "blue"), (2, "cat", "2016-08-02", "blue"), (3, "bird", "2016-07-05", "red"), (4, "cow", "2016-08-04", "red"), (5, "snake", "2016-08-12", "yellow"); 
[localhost:21000] > select * from teams t1 where `timestamp`=(select min(t2.`timestamp`) from teams t2 where t2.team = t1.team); 
+----+--------+---------------------+--------+ 
| id | animal | timestamp   | team | 
+----+--------+---------------------+--------+ 
| 1 | dog | 2016-08-01 00:00:00 | blue | 
| 3 | bird | 2016-07-05 00:00:00 | red | 
| 5 | snake | 2016-08-12 00:00:00 | yellow | 
+----+--------+---------------------+--------+ 
関連する問題