gpt4 book ai didi

mysql - 我想要一个从我的数据库中删除重复条目的查询

转载 作者:行者123 更新时间:2023-11-29 06:14:04 25 4
gpt4 key购买 nike

我写了一个查询delete from Table1 where Tableid in(select Tableid from Table1 group by Tableid having count(*) >1)但是这个查询删除了所有计数大于 1 的数据。

谁能帮我删除重复数据并将计数重置为 1 的单行查询。

我有表 Table1

Tableid Count 

1 10

2 2

3 1

4 NULL

5 31

Post Delete 应该是

Tableid Count 
1 1

2 1

3 1

4 NULL

5 1

最佳答案

我想这就是你要找的

DECLARE @Table TABLE 
(
Name VARCHAR(20),
Value INT
);

;WITH T AS (
SELECT CONCAT('a',1) AS Name, 1 AS Value
UNION ALL
SELECT CONCAT('a',T.Value + 1) AS Name, T.Value + 1 FROM T
WHERE T.Value < 5
)
INSERT INTO @Table
SELECT T.Name ,
T.Value
FROM T


INSERT INTO @Table
( Name, Value )
VALUES ( 'a5', -- Name - varchar(20)
5 -- Value - int
),( 'a5', -- Name - varchar(20)
5 -- Value - int
)

INSERT INTO @Table
SELECT * FROM @Table

INSERT INTO @Table
SELECT * FROM @Table

SELECT
COUNT(*) AS TotalCount
, Name
, Value
FROM
@Table
GROUP BY
Name ,
Value
ORDER BY
Name



DELETE T
FROM (
SELECT
Name
, Value
, ROW_NUMBER() OVER(PARTITION BY Name, Value ORDER BY Value) AS RN
FROM
@Table
) AS T
WHERE T.RN > 1


SELECT COUNT(*) AS TotalCount, Name, Value
FROM @Table
GROUP BY Name, Value
ORDER BY Name, Value

关于mysql - 我想要一个从我的数据库中删除重复条目的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com