简体   繁体   English

SQL查询同一用户的最后日期

[英]SQL query for same user with last date

I have a table with following data. 我有一张包含以下数据的表。 ID, date and type are all primary key. ID,日期和类型都是主键。 ID is person, type is for work type. ID是人,类型是工作类型。

id     date     Type
--------------------------
6   |  2011   |  2
6   |  2012   |  2
6   |  2012   |  3
6   |  2012   |  5
7   |  2013   |  1
7   |  2016   |  1
etc..

I want to create a query that would show both id 6 that have difference type, and take the last date if there is tow row for same ID with same type. 我想创建一个查询,该查询将显示具有差异类型的两个ID 6,如果存在相同类型的相同ID的拖行,则取最后日期。 The result should show same as that. 结果应与此相同。

id     date     Type
--------------------------
6   |  2012   |  2
6   |  2012   |  3
6   |  2012   |  5
7   |  2016   |  1
etc..

You can do this with a correlated subquery: 您可以使用相关子查询来执行此操作:

select t.*
from t
where t.date = (select max(t2.date) from t t2 where t2.id = t.id and t2.type = t.type);

Another way to do it : 另一种方法是:

select a.id, b.date, a.type
 from 
(
    select distinct id, type 
    From Test1 
) a
INNER JOIN 
(
    select distinct id, max(date) date
    From Test1 
    group by id
) b 
on a.id = b.id 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM