如何根据另一列的最大值从一列中选择一个值,如果它们相同,则使用另一列的最大值

时间:2018-04-11 14:50:16

标签: sql oracle

我们说我有这张桌子:

KEY |  PID  |  ID   |  YEAR
___________________________
 1  |  123  | 999   |  2018
 2  |  123  | 999   |  2017
 3  |  123  | 999   |  2016
 4  |  456  | 888   |  2018
 5  |  456  | 999   |  2018
 6  |  456  | 777   |  2018 

我想通过查询具有该特定KEY的最新PID的行来返回唯一的YEAR值和相应的PID。如果两个PIDs具有相同的YEAR,则应检查哪一个ID

例如,预期结果将返回:

1  |  123  
5  |  456 

正如您所看到的,我们会返回1,因为它在IDs的其余部分之间有最新的一年,并且返回了5,因为尽管它们都是相同的YEAR ,它具有最高的ID值。

3 个答案:

答案 0 :(得分:2)

只需使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by pid order by year desc id desc) as seqnum
      from t
     ) t
where seqnum = 1;

假设id唯一的另一种方法是:

select t.*
from t
where t.id = (select maxt2.id) keep (dense_rank first order by t2.id desc)
              from t t2
              where t2.pid = t.pid 
              order by t2.year desc
             );

答案 1 :(得分:0)

SELECT  Key, PID
FROM table
WHERE [YEAR] = (SELECT MAX([YEAR]) FROM dbo.Ptable) 
AND ID = (SELECT MAX(ID) FROM table)

答案 2 :(得分:0)

你可以试试这个。

SELECT DISTINCT T.KEY,T.PID  
FROM T INNER JOIN
(
  SELECT PID,MAX(ID) MAXID
  FROM T
  GROUP BY PID
) T2 ON T2.MAXID = T.ID 
INNER JOIN
(
  SELECT PID,MAX(YEAR) AS YID
  FROM T
  GROUP BY PID
) T3 ON T3.YID = T.YEAR
ORDER BY T.KEY

sqlfiddle:http://sqlfiddle.com/#!4/b30e1/28