从相同的行中删除一行

时间:2011-09-02 17:33:27

标签: sql sql-server

我有一个带有(第一,第二)列的表T.我有两行,第一个= 1,第二个= 2。我想删除其中一行。我该怎么做?

2 个答案:

答案 0 :(得分:4)

;WITH CTE AS
(
SELECT TOP 1 *
FROM YourTable 
WHERE first=1 and second=2
)
DELETE FROM CTE;

或者如果SQL Server 2000

DELETE T
FROM (
    SELECT TOP 1 *
    FROM YourTable 
    WHERE [first]=1 and [second]=2
) T;

然后添加主键。

答案 1 :(得分:3)

您可以使用ROW_NUMBER()。

DECLARE @T as Table(First int , Second int )

INsert Into @T
Values (1,2),
(1,2)

SELECT * FROM @T

;WITH CTE as 
(SELECT ROW_NUMBER() over (order by first,second) rn , * from @T)

DELETE FROM CTE where rn = 1

select * from @T

如果您将rn更改为包含分区

ROW_NUMBER() over (PARTITION BY first, second order by first,second)

并将地点更改为WHERE RN <> 1

您可以将此作为一般解决方案来删除First,Second

上的任何欺骗