删除表中的部分重复行

时间:2011-11-22 12:28:15

标签: sql

我有一个表,包含rowid,userid,productid和times。一旦我按用户ID和时间订购了这张桌子。它看起来像:

u1, t1, p1
u1, t2, p1
u1, t3, p1
u1, t4, p2
u1, t5, p2
u1, t6, p3
u2, t7, p1
u2, t8, p1
u2, t9, p2
u2, t10,p3
 .....

我想删除产品ID与前一行相同的行 因此决赛桌应该是:

u1, t1, p1
u1, t4, p2
u1, t6, p3
u2, t7, p1
u2, t9, p2
u2, t10,p3
.....

我怎样才能在SQL中执行此操作?非常感谢

3 个答案:

答案 0 :(得分:1)

简化版
事实证明它适用于SQL Server,您可以直接在SQL Server中从CTE中删除(正如@Royi Namir在下面的评论中所暗示的那样):

;WITH x AS (
    SELECT rowid,
           rownumber() OVER (PARTITION BY user_id,productid ORDER BY times) AS rn
    FROM   tbl
    )
DELETE FROM x
WHERE  rn > 1;

Simplified live demo at sqlfiddle
Much like this one

答案 1 :(得分:0)

;WITH x AS (
    select rowid,  rownumber() 
            over (partition by userid,productid order by rowid) as rn     
    FROM   tbl
    )
DELETE FROM tbl
    WHERE  tbl.rowid= x.rowid
AND    x.rn > 1

答案 2 :(得分:0)

DECLARE @tmp TABLE( prod VARCHAR(10));

INSERT INTO @tmp SELECT DISTINCT PROD FROM tblSource

SELECT TOP 1 FROM tblSource a
JOIN @tmp b ON a.product = b.prod
ORDER BY UserId, TimeId

我的不好,我没有完全阅读这个问题,因为你想要删除,你可能想要使用Royi的答案。 OTH,你可以把我的选择放到第二个temp中,然后在主表中删除tmp2为null的左连接