sql - 删除sql查询中的重复行
问题描述
我有一个具有以下结构的表
[id] [int] IDENTITY(1,1) NOT NULL,
[account_number] [int] NOT NULL,
[account_name] [varchar(100)] NULL,
[account_chapter] [varchar(20)] NULL,
可以有许多行具有相同的 account_number,但 account_name 和 account_chapters 不同。
例如,我们可以有如下内容:
id account_number account_name account_chapter
12 1111 Name01 chapter01
13 1111 Name02 chapter02
14 2222 Name03 chapter07
15 2222 Name05 chapter11
16 7777 Name06 chapter44
我想要的是一个查询,对于每个 account_number,只过滤表中的第一次出现。例如,上面的查询必须转换为以下内容:
id account_number account_name account_chapter
12 1111 Name01 chapter01
14 2222 Name03 chapter07
16 7777 Name06 chapter44
这是我写的查询:
with req01 as (select distinct account_number from accounts)
select * from req01 full join (select * from accounts) as p on p.account_number = req01.account_number
它不会产生预期的结果。
有什么帮助吗?谢谢。
解决方案
使用ROW_NUMBER
:
SELECT TOP 1 WITH TIES *
FROM accounts
ORDER BY ROW_NUMBER() OVER (PARTITION BY account_number ORDER BY account_chapter);
或者,ROW_NUMBER
以更典型的方式使用:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY account_number
ORDER BY account_chapter) rn
FROM accounts
)
SELECT id, account_number, account_name, account_chapter
FROM cte
WHERE rn = 1;
请注意,这两个答案都假定account_chapter
版本确定哪个“重复”实际上是第一个。
推荐阅读
- netlogo - netlogo - 随机转发 -
- javascript - 如何将 DataTables 的本地化更改为德语
- jenkins - 如何启用多字符串参数和文件参数,基于之前在 Jenkins 中的参数选择?
- bash - 如何编写一个bash脚本来计算一个文件夹的所有文件的前n个字节的md5和
- java - Javers.commit() 不工作 MANAGED_CLASS_MAPPING_ERROR
- audio-recording - 如何实现 Nvidia ShadowPlay 之类的录音
- performance - Neo4j 加载 csv 性能问题
- python-3.x - “无法加载本机 TensorFlow 运行时。” 在 cpu 张量流中
- gcc - 从 TCL 执行 cpp/exe
- java - Jackson ObjectMapper 在转换为 POJO 时会忽略某些键