简体   繁体   English

SQL 查询从同一个表中获取不同的值

[英]SQL query to fetch distinct values from same table

Let's say I have this table: employeetable:假设我有这张表:employeetable:

empid空的 joindate加入日期 location地点 HRupdatedate人力资源更新日期 Changes变化
1 1 2002-01-05 2002-01-05 Delhi德里 2021-03-01 2021-03-01 New新的
2 2 2009-09-09 2009-09-09 Mumbai孟买 2021-03-05 2021-03-05 New新的
1 1 2010-06-27 2010-06-27 Hyderabad海得拉巴 2021-03-03 2021-03-03 Transfer转移
2 2 2015-11-02 2015-11-02 Delhi德里 2021-03-06 2021-03-06 Transfer转移
3 3 2020-01-01 2020-01-01 Mumbai孟买 2021-03-06 2021-03-06 New新的
4 4 2007-07-30 2007-07-30 Delhi德里 2021-03-04 2021-03-04 New新的

I want to get data from this table where empid in (1,2,4).我想从这个表中获取数据,其中 empid 在 (1,2,4) 中。 That will return:这将返回:

empid空的 joindate加入日期 location地点 HRupdatedate人力资源更新日期 Changes变化
1 1 2002-01-05 2002-01-05 Delhi德里 2021-03-01 2021-03-01 New新的
2 2 2009-09-09 2009-09-09 Mumbai孟买 2021-03-05 2021-03-05 New新的
1 1 2010-06-27 2010-06-27 Hyderabad海得拉巴 2021-03-03 2021-03-03 Transfer转移
2 2 2015-11-02 2015-11-02 Delhi德里 2021-03-06 2021-03-06 Transfer转移
4 4 2007-07-30 2007-07-30 Delhi德里 2021-03-04 2021-03-04 New新的

But I only need the latest record without the duplicate entries:但我只需要没有重复条目的最新记录:

empid空的 joindate加入日期 location地点 HRupdatedate人力资源更新日期 Changes变化
1 1 2010-06-27 2010-06-27 Hyderabad海得拉巴 2021-03-03 2021-03-03 Transfer转移
2 2 2015-11-02 2015-11-02 Delhi德里 2021-03-06 2021-03-06 Transfer转移
4 4 2007-07-30 2007-07-30 Delhi德里 2021-03-04 2021-03-04 New新的

How to achieve this?如何做到这一点?

You can use top with ties你可以用top with ties

select top(1) with ties *
from employeetable
where empid in (1,2,4)
order by row_number() over(partition by empid order by joindate desc)

You can easily achieve this by using WHERE clause.您可以使用WHERE子句轻松实现此目的。

select * from  
employeetable et1
where 
    joindate = (
        select max(joindate)
            from employeetable et2 
            where et1.empid = et2.empid
    ) 
    and 
    empid in (1,2, 4);

Or for more precise results或者为了更精确的结果

select * from  
employeetable et1
where 
    joindate = (
        select max(joindate)
            from employeetable et2 
            where et1.empid = et2.empid
    ) 
    and 
    HRupdatedate = (
        select max(HRupdatedate)
            from employeetable et2 where et1.empid = et2.empid
    )
    and 
    empid in (1,2, 4);

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

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