[英]SQL query to fetch distinct values from same table
Let's say I have this table: employeetable:假设我有这张表:employeetable:
empid![]() |
joindate![]() |
location![]() |
HRupdatedate![]() |
Changes![]() |
---|---|---|---|---|
1 ![]() |
2002-01-05 ![]() |
Delhi![]() |
2021-03-01 ![]() |
New![]() |
2 ![]() |
2009-09-09 ![]() |
Mumbai![]() |
2021-03-05 ![]() |
New![]() |
1 ![]() |
2010-06-27 ![]() |
Hyderabad![]() |
2021-03-03 ![]() |
Transfer![]() |
2 ![]() |
2015-11-02 ![]() |
Delhi![]() |
2021-03-06 ![]() |
Transfer![]() |
3 ![]() |
2020-01-01 ![]() |
Mumbai![]() |
2021-03-06 ![]() |
New![]() |
4 ![]() |
2007-07-30 ![]() |
Delhi![]() |
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 ![]() |
2002-01-05 ![]() |
Delhi![]() |
2021-03-01 ![]() |
New![]() |
2 ![]() |
2009-09-09 ![]() |
Mumbai![]() |
2021-03-05 ![]() |
New![]() |
1 ![]() |
2010-06-27 ![]() |
Hyderabad![]() |
2021-03-03 ![]() |
Transfer![]() |
2 ![]() |
2015-11-02 ![]() |
Delhi![]() |
2021-03-06 ![]() |
Transfer![]() |
4 ![]() |
2007-07-30 ![]() |
Delhi![]() |
2021-03-04 ![]() |
New![]() |
But I only need the latest record without the duplicate entries:但我只需要没有重复条目的最新记录:
empid![]() |
joindate![]() |
location![]() |
HRupdatedate![]() |
Changes![]() |
---|---|---|---|---|
1 ![]() |
2010-06-27 ![]() |
Hyderabad![]() |
2021-03-03 ![]() |
Transfer![]() |
2 ![]() |
2015-11-02 ![]() |
Delhi![]() |
2021-03-06 ![]() |
Transfer![]() |
4 ![]() |
2007-07-30 ![]() |
Delhi![]() |
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.