如何按排序顺序从表中删除后续重复行?

时间:2017-03-04 08:45:51

标签: sql sql-server

我有一张简单的表格:

CREATE TABLE [dbo].[FreqLeeds] (
    [Id]   INT             NOT NULL,
    [Freq] DECIMAL (18, 5) NOT NULL,
    [Text] NVARCHAR (50)   NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

“文本”列中的数据应该是唯一的,但事实并非如此。有没有办法可以保留Text的第一个值(按Freq的顺序排序)并删除所有其他具有重复值的行?

3 个答案:

答案 0 :(得分:0)

在您的情况下,您需要唯一的索引键。

但首先,你需要清除重复的项目;然后创建唯一索引以防止将来出现脏数据:

-- Create a unique index 
CREATE UNIQUE INDEX ix_freqleeds_text   
   ON dbo.FreqLeeds ([Text]);   
GO

答案 1 :(得分:0)

如果您需要Id和Text值:

SELECT FIRST_VALUE(Id) OVER (PARTITION BY Text ORDER BY Freq ASC) as Id,
       MIN(Freq) as Freq,
       Text 
    FROM FreqLeeds 
    GROUP BY Text 
    ORDER BY Freq

https://msdn.microsoft.com/en-us/library/hh213018.aspx

答案 2 :(得分:0)

我建议CTE执行此操作:

;with cte
as (
    select t.*,
        row_number() over (
            partition by [Text] order by [Freq]
            ) rn
    from [dbo].[FreqLeeds] t
    )
delete
from cte
where rn <> 1

[Text]行保留一行最小 [Freq]并删除所有其他行。如果您希望每[Text]行保留一行最大 [Freq],请在窗口函数中使用order by [Freq] desc