从另一列的最大值中检索列的最小值

时间:2017-12-08 00:43:51

标签: sql hive

我有一个hive表t1,如下所示:

ID   Score1    score2  
1     4         11  
1     5         12  
1     5         13  
2     3         14  
2     3         15  
2     2         12  
2     2         11  
3     6         10  
3     6         11  
3     6         12  

我想要每个ID,选择score1的最大值,如果最大值存在多次,那么从包含max(score1)的行中我想获得min(score2)。

所以,我想要最高得分1行的最低得分2,结果应该是这样的

ID    Score1    score2  
1     5         12  
2     3         14  
3     6         10  

我将大多数想法变成了一个非常复杂的查询,我认为有一个简单的解决方案,我还无法找到它。

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

使用窗口功能:

list'1.Add(<WRM.Common.RiskCalculation.Tests.ModData>)

答案 1 :(得分:0)

select id, min(score2)
from table1 t
inner join (
   select id, max(score1) maxscore1 group by id
    )  d on t.id = d.id and t.score1 = d.maxscore1
group by t.id
having count(*) > 1 # if the max value exists more than once

替代查询,如果db支持&#34;分析函数&#34;,则

select
     id, min(score2)
from (
      select id, score1, score2
            , count(case when score1 = max(score1) over(partition by id) then 1 end) count_max
      from table1
      ) d
where count_max > 1 -- if the max value exists more than once
group by
     id

答案 2 :(得分:0)

尝试:

SELECT Z.ID, Z.SCORE1, MIN(SCORE2) AS SCORE2
FROM
(SELECT A.ID, A.SCORE FROM
YOUR_TABLE A
INNER JOIN
(SELECT ID, MAX(SCORE1) FROM YOUR_TABLE GROUP BY ID) B
ON A.ID = B.ID AND A.SCORE1 = B.SCORE1
GROUP BY A.ID, A.SCORE
HAVING COUNT(*)>1 
) Z
INNER JOIN YOUR_TABLE C
ON Z.ID = C.ID AND Z.SCORE1 = C.SCORE1
GROUP BY Z.ID, Z.SCORE1;

答案 3 :(得分:0)

您可以使用窗口函数执行此操作:

SELECT ID,score1,MIN(score2)AS score2 FROM(   SELECT score1,score2,ID   FROM(     SELECT score1,score2,ID     来自MyTable     资格等级(按分数除以ID1 DESC)&gt; 1   )src   QUALIFY COUNT()OVER(按ID划分)&gt; 1 )src GROUP BY 1,2

抱歉,从我的手机中写这个...无法很好地格式化,也可能存在语法错误。