[英]Select row only on a max field
id name school date
1 John QVS 1/3/2000
1 John RKS 1/4/2008
2 Sera ACS 1/2/2009
2 Sera WCS 1/4/2011
3 Jack YUN 1/4/2014
3 Jack KIL 1/3/2017
名称,学校和日期都来自不同的表,即名称,学校和日期以及内部联接。
我只想选择最新日期的行。 结果应为:
id name school date
1 John RKS 1/4/2008
2 Sera WCS 1/4/2011
3 Jack KIL 1/3/2017
尝试这个:
select * from table t1 where not exists ( select 1 from table t2 where t1.id = t2.id and t1.name = t2.name and t1.date < t2.date )
您可以使用它。 希望它对您有用。
SELECT
tb1.id
,tb1.name
,tb1.school
,tb1.[date]
FROM
yourTable tb1
where [date] IN
(
SELECT MAX([date]) FROM yourTable tb2 WHERE tb1.id = tb2.id GROUP BY tb2.id
)
您可以使用Row_number
。 如果您希望所有行都具有最新日期,请使用dense_rank
或rank
;with temp as
(
select id,
name,
school,
[date],
Row_number() over(partition by id order by [date] desc) as [Rn]
-- rank()\dense_rank() to get all latest date.
from yourTable
)
select id,
name,
school,
[date]
from temp
where Rn = 1
演示链接: http : //rextester.com/YTH8889
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.