如果有多个相同的 ID,Where 子句

Where clause if there are multiple of the same ID(如果有多个相同的 ID,Where 子句)
本文介绍了如果有多个相同的 ID,Where 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

ID | source | Name | Age | ... | ...
1  | SQL    | John | 18  | ... | ...
2  | SAP    | Mike | 21  | ... | ...
2  | SQL    | Mike | 20  | ... | ...
3  | SAP    | Jill | 25  | ... | ...

我希望每个 ID 都有一个记录.这背后的想法是,如果 ID 只出现一次(无论来源如何),则将采用该记录.但是,如果一个 ID 有 2 条记录,那么以 SQL 作为源的记录将是这里使用的记录.

I want to have one record for each ID. The idea behind this is that if the ID comes only once (no matter the Source), that record will be taken. But, If there are 2 records for one ID, the one containing SQL as source will be the used record here.

所以,在这种情况下,结果将是:

So, In this case, the result will be:

ID | source | Name | Age | ... | ...
1  | SQL    | John | 18  | ... | ...
2  | SQL    | Mike | 20  | ... | ...
3  | SAP    | Jill | 25  | ... | ...

我是通过一个分区完成的(按 Source desc 排序),但如果有一天会添加第三个源,这将无法正常工作.

I did this with a partition over (ordered by Source desc), but that wouldn't work well if a third source will be added one day.

还有其他选择/想法吗?

Any other options/ideas?

推荐答案

最简单的方法(在我看来)是使用带有排名功能的 CTE:

The easiest approach(in my opinion) is using a CTE with a ranking function:

with cte as
(
   select ID, source, Name, Age, ... , 
          rn = row_number() over (partition by ID order by case when source = 'sql'
                                                           then 0 else 1 end asc)
   from dbo.tablename
)
select ID, source, Name, Age, ...
from cte
where rn = 1

这篇关于如果有多个相同的 ID,Where 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)