如何根据sql中的条件过滤重复行?
How to filter duplicate rows based on a condition in tsql?
我有一名员工 table 有重复的记录,包括雇用合同或更换徽章的详细信息。
FullName
Status
Current Position
John Doe
Inactive
Finance Analyst
John Doe
Active
Finance Manager
Mike Wood
Active
Project Manager
Mike Wood
Inactive
Consultant
Sam Hyke
Inactive
Director
Ahmed Saeed
Active
Supply Chain Manager
我想 select 所有记录,不管状态如何,只有在重复的情况下,它应该过滤并选择状态为 'Active' 的行。
预期结果
FullName
Status
Current Position
John Doe
Active
Finance Manager
Mike Wood
Active
Project Manager
Sam Hyke
Inactive
Director
Ahmed Saeed
Active
Supply Chain Manager
select top 1 with ties FullName,Status,[Current Position]
from yourtable
order by row_number() over(partition by FullName order by case Status when 'Active' then 1 else 0 end)
您可以 select DISTINCT
FullName
,按 FullName
、Status
、
订购 table
SELECT DISTINCT FullName,
Status,
[Current Position]
FROM employees
ORDER BY FullName, Status;
重新排序后,'Active'
将始终排在第一位。 (如果存在)
试试这个:
select top 1 with ties full_name "Full Name",Status,current_position "Current Position"
from employee
order by row_number() over(partition by full_name order by case Status when 'Active' then 0 else 1 end)
我有一名员工 table 有重复的记录,包括雇用合同或更换徽章的详细信息。
FullName | Status | Current Position |
---|---|---|
John Doe | Inactive | Finance Analyst |
John Doe | Active | Finance Manager |
Mike Wood | Active | Project Manager |
Mike Wood | Inactive | Consultant |
Sam Hyke | Inactive | Director |
Ahmed Saeed | Active | Supply Chain Manager |
我想 select 所有记录,不管状态如何,只有在重复的情况下,它应该过滤并选择状态为 'Active' 的行。
预期结果
FullName | Status | Current Position |
---|---|---|
John Doe | Active | Finance Manager |
Mike Wood | Active | Project Manager |
Sam Hyke | Inactive | Director |
Ahmed Saeed | Active | Supply Chain Manager |
select top 1 with ties FullName,Status,[Current Position]
from yourtable
order by row_number() over(partition by FullName order by case Status when 'Active' then 1 else 0 end)
您可以 select DISTINCT
FullName
,按 FullName
、Status
、
SELECT DISTINCT FullName,
Status,
[Current Position]
FROM employees
ORDER BY FullName, Status;
重新排序后,'Active'
将始终排在第一位。 (如果存在)
试试这个:
select top 1 with ties full_name "Full Name",Status,current_position "Current Position"
from employee
order by row_number() over(partition by full_name order by case Status when 'Active' then 0 else 1 end)