1

在 MSSQL TABLE 我有 3 列。

ID (IDENTITY), KeptValue(NVARCHAR), SPENT(MONEY).

我有多个KeptValue重复的 s。我需要删除所有重复项并保留 1 个。但我需要保留花费最多的那个。
我创建了 2 个视图。重复保留值的列表VW_DUPLICATE1

4

5 回答 5

2
delete t1
from your_table t1
left join  
(
   select keptvalue, max(spent) as mSpent
   from your_table
   group by keptvalue

) t2 on t1.keptvalue = t2.keptvalue and t1.spent = t2.mSpent
where t2.mSpent is null
于 2013-07-09T11:08:06.287 回答
0

尝试这个

DELETE FROM tbl WHERE Id IN (
    SELECT Id FROM (
        SELECT 
            Id
            ,ROW_NUMBER() OVER (PARTITION BY KeptValue ORDER BY SPENT DESC) AS [ItemNumber]
        FROM 
            tbl
    ) a WHERE ItemNumber > 1 
)
于 2013-07-09T11:56:20.247 回答
0

您可以使用此查询通过特定KepValue保留最高删除SPENT

DELETE FROM your_table WHERE SPENT < (SELECT MAX(SPENT) FROM your_table WHERE KeptValue='your_value') AND KeptValue='your_value'
于 2013-07-09T11:46:33.520 回答
0

尝试这个

Create table #temp ( ID int, KeptValue NVARCHAR(20) , SPENT numeric(18,3))

INSERT INTO #temp select 1,'KeptValue1', 20
INSERT INTO #temp select 2,'KeptValue1', 21
INSERT INTO #temp select 3,'KeptValue2', 22
INSERT INTO #temp select 4,'KeptValue2', 20
INSERT INTO #temp select 5,'KeptValue2', 20
INSERT INTO #temp select 6,'KeptValue3', 20
INSERT INTO #temp select 7,'KeptValue3', 23
INSERT INTO #temp select 8,'KeptValue3', 24
INSERT INTO #temp select 9,'KeptValue4', 28
INSERT INTO #temp select 10,'KeptValue4', 23
INSERT INTO #temp select 11,'KeptValue5', 24
INSERT INTO #temp select 12,'KeptValue6', 28

select * FROM #temp 

DELETE 
FROM #temp 
WHERE ID 
in(
    select ID from  
                    (SELECT Id, (ROW_NUMBER() OVER(PARTITION BY KeptValue order by SPENT desc)) as R 
                    from #temp
                    ) as RowsNm
    WHERE R >1)

select * from #temp 


drop table #temp 
于 2013-07-09T11:58:57.357 回答
-1

您可以通过在 Spent 上执行group byKeptValue 和max聚合来实现此目的

于 2013-07-09T11:04:12.837 回答