sql PARTITION组内去重
时间: 2023-09-20 20:06:32 浏览: 91
几种sql去重
5星 · 资源好评率100%
在SQL中,要实现PARTITION组内的去重,常用的方法是使用ROW_NUMBER()函数结合PARTITION BY子句和ORDER BY子句。首先,使用PARTITION BY子句指定要进行去重的字段,然后使用ORDER BY子句指定排序字段的顺序。最后,在SELECT语句中使用ROW_NUMBER()函数来给每一行分配一个行号。通过将这个行号与值为1的条件进行比较,就可以筛选出每个组内的唯一记录。举个例子,假设我们有一个表名为"infos",其中包含字段"field1"和"field2",我们想要在"field1"字段的值相同的组内进行去重,可以使用以下语句实现:
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY field1 ORDER BY field2) AS rowNum
FROM infos
) AS temp
WHERE rowNum = 1
这个查询会在每个field1值相同的组内,按照field2的顺序给每一行分配一个行号。最后,我们只选择行号为1的记录,即每个组内的唯一记录。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [浅谈sql数据库去重](https://download.csdn.net/download/weixin_38675777/13690747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [SQl 根据某列去重 partition by](https://blog.csdn.net/weixin_39572442/article/details/113543071)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [SQL server 多条数据根据其中一个字段去重并返回所有列 row_number() over (partition by 要去重的字段 ...](https://blog.csdn.net/YL3126/article/details/117224259)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文