我有这张桌子
我想删除连续的类似行并保留最近的行。 所以我想要的结果是这样的
答案 0 :(得分:0)
我将如何做到这一点:
;WITH cte AS (
SELECT valeur, date_reference, id, rownum = ROW_NUMBER() OVER (ORDER BY date_reference) FROM #temperatures
UNION ALL
SELECT NULL, NULL, NULL, (SELECT COUNT(*) FROM #temperatures) + 1
)
SELECT A.* FROM cte AS A INNER JOIN cte AS B ON A.rownum + 1 = B.rownum AND COALESCE(a.valeur, -459) != COALESCE(b.valeur, -459)
我正在调用表#temperatures。使用CTE为每条记录分配ROW_NUMBER
并包含最后一条Row_Number
的额外记录(否则最后一条记录将不包含在以下查询中)。然后,来自CTE的SELECT
,其中下一个ROW_NUMBER
没有相同的valeur
。
现在,如果您想要从原始表中DELETE
,您可以查看此查询的返回,以确保您确实要删除此返回中不包含的所有记录。然后,假设historique_id
是主键DELETE FROM #temperatures WHERE historique_id NOT IN (SELECT historique_id FROM cte AS A...
。
答案 1 :(得分:0)
您可以收集要保存在临时表中的所有行,truncate
原始表,并将临时表中的所有行插入到原始表中。这比仅仅删除行更有效,以防你有很多重复"。 truncate table
也有以下限制
您不能在以下表格上使用TRUNCATE TABLE:
在Azure SQL数据仓库和并行数据仓库中:
您可以在以下主题中找到更多信息。
Deleting Data in SQL Server with TRUNCATE vs DELETE commands
您可以使用此脚本通过truncate-insert策略删除重复行
CREATE TABLE #temp_hisorique(
code varchar(50),
code_trim varchar(50),
libelle varchar(50),
unite varchar(50),
valeur varchar(50),
date_reference datetime,
hisoriqueID int
)
GO
;WITH cte AS (
select *, row_number() over(partition by code, code_trim, libelle, unite, valeur order by date_reference desc) as rownum
from mytable
)
insert into #temp_hisorique(code, code_trim, libelle, unite, valeur, date_reference, hisoriqueID)
select code, code_trim, libelle, unite, valeur, date_reference, hisoriqueID
from cte
where rownum = 1
TRUNCATE TABLE mytable
insert into mytable(code, code_trim, libelle, unite, valeur, date_reference, hisoriqueID)
select code, code_trim, libelle, unite, valeur, date_reference, hisoriqueID
from #temp_hisorique
或者你可以通过delete命令删除行。
;WITH cte AS (
select *, row_number() over(partition by code, code_trim, libelle, unite, valeur order by date_reference desc) as rownum
from mytable
)
delete T
from mytable T
join cte on T.hisoriqueID = cte.hisoriqueID
where cte.rownum > 1