如何选择表格中的第一行

时间:2016-08-19 16:42:57

标签: sql hive

我正在尝试为每种类型(A,B,C,......等)选择第一次出现的“质量”列

infotable
--------
time   Type   quality
1:00   A      1
1:05   A      1
1:10   A      2
1:13   A      2
1:17   A      3
1:20   B      3
1:22   B      2
1:25   B      2
1:30   B      1

and i want the final result to be like this:
--------------------------
time   Type   quality
1:00   A      1
1:10   A      2
1:17   A      3
1:20   B      3
1:22   B      2
1:30   B      1

我试图通过多次CTE但未能获得正确的输出

with 
  cte_type
as (
  select *,
  row_number() over (partition by type order by time asc ) as rn_type
  from infotable
  ),
  cte_quality
  as (
  select *,
  row_number() over (partition by quality order by time asc ) as rn_quality
  from cte_type
  )
select * from cte_quality
where rn_quality = 1;

对我如何获得所需结果的任何想法都会非常感激

3 个答案:

答案 0 :(得分:2)

我认为它应该像

FB.getLoginStatus(function(response) {
//only works when page loads, use FB.Event.subscribe for status change      
    statusChangeCallback(response);
    FB.Event.subscribe('auth.statusChange', function(response){
        //yay! do whatever here, there was a status change
    },true);  

});

答案 1 :(得分:0)

您只需要一个cte / row_number:

with 
  cte
as (
  select *,
     row_number()
     over (partition by type, quality 
           order by time asc ) as rn
  from infotable
  )
select * from cte
where rn = 1;

答案 2 :(得分:0)

不需要cte

Select Time, Type, Quality
From infotable it
Where time =
   (Select Min(time)
    From infotable
    Where type = it.Type
       and Quality = it.Quality)

这也会告诉您类型和行列是否有多行。质量同时。