如何使用过滤器删除重复的行

时间:2015-08-07 07:56:35

标签: sql-server tsql sql-server-2008-r2

有表格:

declare @tbl TABLE (id int,sub_id int,[money] money)
insert into @tbl (id,sub_id,money)
SELECT 289,33602502,800.00
UNION ALL
SELECT 300,33602502,805.00
UNION ALL
SELECT 735,33603527,7175.77
UNION ALL
SELECT 741,33603527,7172.77
UNION ALL
SELECT 2049,33606066,4817.77
UNION ALL
SELECT 2060,33606066,4791.77
UNION ALL
SELECT 2598,33607099,4084.77
UNION ALL
SELECT 2605,33607099,4053.77

要删除sub_id相同且money字段为min的行。 例如,响应必须如下:

id   sub_id      money
289 33602502    800.00
741 33603527    7172.77
2060 33606066   4791.77
2605 33607099   4053.77

怎么做?

3 个答案:

答案 0 :(得分:1)

试试这个:

DELETE FROM @tbl WHERE id in(
select t1.id from @tbl t1
inner join @tbl t2 on t1.sub_id = t2.sub_id
WHERE t1.money > t2.money)

select * from @tbl

答案 1 :(得分:1)

您应该使用OVER Clause执行此类任务。 这将删除每个sub_id的资金最低的行:

;WITH cte as
(
  SELECT *, row_number() over (partition by sub_id order by money) rn from @tbl
)
DELETE cte where rn = 1

答案 2 :(得分:0)

declare @tbl TABLE (id int,sub_id int,[money] money)
insert into @tbl (id,sub_id,money)
SELECT 289,33602502,800.00
UNION ALL
SELECT 300,33602502,805.00
UNION ALL
SELECT 735,33603527,7175.77
UNION ALL
SELECT 741,33603527,7172.77
UNION ALL
SELECT 2049,33606066,4817.77
UNION ALL
SELECT 2060,33606066,4791.77
UNION ALL
SELECT 2598,33607099,4084.77
UNION ALL
SELECT 2605,33607099,4053.77


delete from t from  @tbl t
inner join (    
select sub_id,MIN(money)as money from @tbl
group by sub_id
) p on p.sub_id=t.sub_id and p.money=t.money


select * from @tbl