从sql中的重复记录中仅删除1行

时间:2015-11-24 06:05:37

标签: sql sql-server

我有这样的查询:

Select * From T_Trans_HHT Where transType='OUT' and docNum='15/01979' order by ItemCode

我得到这样的重复记录:我的每个项目代码都会出现2次,所以我想从我的表中删除一个项目代码行? 我的出局是这样的: enter image description here

在这个我想删除一行,我怎么能这样做?

4 个答案:

答案 0 :(得分:2)

使用CTE和Row_number

 ;with CTE AS 
    (Select *,ROW_NUMBER()OVER(PARTITION BY Docnum,location
     ORDER BY transDATEtime desc)RN 
    From T_Trans_HHT 
    Where transType='OUT' and 
    docNum='15/01979' )

    delete from CTE where RN = 1

或使用

DISTINCT and Group BY all columns 
select distinct col1,col2 ... from table
Group by all columns

答案 1 :(得分:1)

DELETE TOP(1) From T_Trans_HHT 
Where transType='OUT' 
and docNum='15/01979' 
order by ItemCode

答案 2 :(得分:0)

使用ROW_NUMBER()CTE

<强>查询

;WITH CTE AS
(
    SELECT rn = ROW_NUMBER() OVER
    (
        PARTITION BY ItemCode
        ORDER BY ItemCode
    ), * FROM T_Trans_HHT 
    WHERE transType='OUT' 
    AND docNum='15/01979'
)
DELETE FROM CTE 
WHERE RN > 1;

答案 3 :(得分:0)

这对我有用

SET ROWCOUNT 1
DELETE FROM [table] WHERE ....
SET ROWCOUNT 0