SQL Server 重复记录

2023-02-08数据库问题
2

本文介绍了SQL Server 重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

您好,我已经完成了以下查询:

Hello I have done the following query below:

UPDATE [dbo].[TestData]
SET Duplicate = 'Duplicate within'
WHERE exists 
(SELECT telephone, COUNT(telephone)
FROM [dbo].[TestData]
GROUP BY telephone
HAVING (COUNT (telephone)>1))

在那个表中实际上有 9 个重复的电话记录.

In that table there are actually 9 duplicate telephone records.

查询将整个重复列标记为重复范围内",而不是 9 条记录.

The query is stamping the entire duplicate column as 'Duplicate within' instead of the 9 records.

我还开发了下一个以下查询,它将 18 个重复记录取消标记为 9 个.

The next following query I have also developed which will unstamp the 18 duplicate records to 9.

UPDATE [dbo].[TestData]
SET Duplicate = 'NO'
WHERE ID IN (SELECT MIN(ID) FROM [dbo].[TestData] GROUP BY telephone)

此查询不起作用,也没有人请指导我哪里出错了!

This query is not working neither could anyone please guide me on where I am going wrong!

推荐答案

您可以使用 where exists,但这种方式更容易编写/读取,并且性能差异很可能很小.

You could do this using where exists, but it's easier to write/read this way and the performance difference is most likely minimal.

update TestData set 
    Duplicate = 'Duplicate within'
where 
    Telephone in (
        select Telephone 
        from TestData 
        group by Telephone 
        having count(*) > 1
    )

要单独保留每个电话号码的第一条记录并仅标记具有相同电话号码的后续记录,请使用 cte,如下所示:

To leave the first record with each telephone number alone and mark only the subsequent records with the same telephone number, use a cte as follows:

;with NumberedDupes as (
    select
        Telephone,
        Duplicate,
        row_number() over (partition by Telephone order by Telephone) seq
    from TestData
)
update NumberedDupes set Duplicate = 'Duplicate within' where seq > 1

这篇关于SQL Server 重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12