我想在SQL Server中删除我的重复值。所以我找到了一个可以找到它们的查询,如何将delete语句附加到此查询中以删除它们?
(SELECT
DocumentNumber, LineNumber, SheetNumber, Unit, COUNT(*)
FROM
Lines
GROUP BY
DocumentNumber, LineNumber, SheetNumber, Unit
HAVING
COUNT(*) > 1)
答案 0 :(得分:5)
我会使用CTE和排名函数ROW_NUMBER
:
;WITH CTE AS
(
SELECT Id, DocumentNumber, LineNumber, SheetNumber, Unit,
RN = ROW_NUMBER() OVER (PARTITION BY DocumentNumber, LineNumber, SheetNumber, Unit
ORDER BY Id DESC) -- keeps the newest Id-row
FROM dbo.Lines
)
DELETE FROM CTE WHERE RN > 1
非常有益,它更易于阅读和维护,并且很容易将其更改为SELECT * FROM CTE
以查看您要删除的内容。
修改Order By
部分以实现自定义逻辑,以保留要保留的行以及要删除的行。它可以包含多个列(ASC或DESC)甚至条件语句(f.e. with CASE
)。
答案 1 :(得分:1)
以下是一些方法:
$key['time_stamp'] = '2016-09-02 16:56:25';
$datetime1 = strtotime(date($key['time_stamp']));
$datetime2 = strtotime(date('Y-m-d H:m:s'));
$interval = $datetime2 - $datetime1;
$val = 45 * 60 * 1000;
if ($interval > $val) { }
或者你也可以使用表变量或CTE或IN和子查询,如果你有一个像ID这样的列
答案 2 :(得分:1)
使用EXISTS
DELETE a
FROM lines a
WHERE EXISTS (SELECT 1
FROM lines b
WHERE a.documentnumber = b.documentnumber
AND a.linenumber = b.linenumber
AND a.sheetnumber = b.sheetnumber
AND a.unit = b.unit
HAVING Count(*) > 1)
使用COUNT() OVER()
;WITH cte
AS (SELECT id,
documentnumber,
linenumber,
sheetnumber,
unit,
CNT = Count(1) OVER(partition BY documentnumber, linenumber, sheetnumber, unit)
FROM dbo.lines)
DELETE FROM cte
WHERE cnt > 1
注意:我的两种方法都会删除此组合documentnumber, linenumber, sheetnumber, unit
的所有记录(如果它是重复的)