仅在最大字段上选择行

时间:2017-06-20 00:42:29

标签: sql sql-server

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

3 个答案:

答案 0 :(得分:0)

试试这个:

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 )

答案 1 :(得分:0)

你可以用它。我希望它对你有用。

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
)

答案 2 :(得分:0)

您可以使用Row_number。 如果您希望所有行都包含最新日期,请使用dense_rankrank

;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

相关问题