【问题标题】:How to filter duplicate rows based on a condition in tsql?如何根据sql中的条件过滤重复行?
【发布时间】:2021-11-24 15:30:27
【问题描述】:

我有一个包含重复记录的员工表,其中包含雇佣合同或重新标记详细信息。

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

我想选择所有记录而不考虑状态,并且仅在重复的情况下,它应该过滤并选择状态为“活动”的行。

预期结果

FullName Status Current Position
John Doe Active Finance Manager
Mike Wood Active Project Manager
Sam Hyke Inactive Director
Ahmed Saeed Active Supply Chain Manager

【问题讨论】:

标签: sql tsql filter duplicates


【解决方案1】:
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)

【讨论】:

  • 这将优先选择非活动。
  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
【解决方案2】:

您可以选择DISTINCTFullName,按FullName、Status订购表格。

SELECT DISTINCT FullName,
       Status,       
       [Current Position]
FROM employees
ORDER BY FullName, Status;

重新排序后,'Active' 将始终位于首位。 (如果存在)

【讨论】:

  • 这仍然会给我非活动状态的副本。
【解决方案3】:

试试这个:

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)

【讨论】:

  • 再次,它与 George 在此线程中给出的查询相同。
  • 一些修改。请运行它,您将获得预期的输出。 imgur.com/a/0UwG2X0
  • 不错不错。谢谢,乔治和赛义德。我的查询中有一个小错误。现在还有另一个问题,比如 John A. Doe 等带有更多首字母的名字。我们可以将上述内容同时应用于两个列,例如名字和姓氏吗?
猜你喜欢
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2021-01-27
  • 2019-07-29
相关资源
最近更新 更多