我有一个 SQL 问题,但我无法处理。
我需要从表中删除一些行,这些行在 date_to 列中为 NULL,但与 date_from 列具有不同的值。
我要删除的列是编号为 3 的列。
它与 date_from 具有相同的值并且为 null。
这是我自己的方法:
select
date_from, id, count(*) number_of_rows_with_the_same_datefrom
from
test
group by
date_from, id
having
count(*) > 1
这将返回具有相同 ID 的相同起始日期的所有行,从那里我迷失了:)
最佳答案
另一种选择是使用 CTE 和 Row_Number()
;with cte as (
Select *
,RN=Row_Number() over (Partition By ID, date_from Order by date_to Desc)
From YourTable
)
Select * --<< Remove if Satisfied
--Delete --<< Remove comment if Statisfied
From cte
Where RN>1 and date_to is null
返回(待删除记录)
ID name date_from date_to RN
2 Jim 2012-08-01 NULL 2
关于sql-server - 从表中删除 NULL 且具有相同 DATE 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550131/