我们说我有这张桌子:
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
值。
答案 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