T-SQL从表中删除重复项?

时间:2016-10-28 01:24:26

标签: sql-server-2008 tsql

我们有一个列出png图像及其源URL的表。

有时,表格的行具有相同的图片网址,但图像像素的宽度和高度不同。我想删除这样的副本,只保留具有最大图像宽度然后最大图像高度的副本。

我已经尝试了以前在MSAccess中使用的各种方法(例如GroupBy和First但是例如在SQL Server中不可用,所以我想要求T-SQL帮助)。

任何人都可以提供可以删除重复项的T-SQL(保留每个副本的最大图像行)吗?

CREATE TABLE [dbo].[tblImageSuggestions]
(
    [CounterID] [bigint] IDENTITY(700996,1) NOT NULL,
    [CreatedDateTime] [datetime] NOT NULL,
    [EmailAddress] [nvarchar](200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ImageOriginalURL] [nvarchar](2000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ImageOriginalWidthPixels] [int] NOT NULL,
    [ImageOriginalHeightPixels] [int] NOT NULL,

    CONSTRAINT [PK_tblImageSuggestions] 
        PRIMARY KEY CLUSTERED ([CounterID] ASC)
                WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
                     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, 
                     ALLOW_PAGE_LOCKS  = ON)
)

SET IDENTITY_INSERT [dbo].[tblImageSuggestions] ON

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701030, CAST(0x0000A6AD0005543F AS DateTime), N'webmaster@mysite.org', N'MyURL1', 1024, 1024)

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701031, CAST(0x0000A6AD00055445 AS DateTime), N'webmaster@mysite.org', N'MyURL2', 450, 450)

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701032, CAST(0x0000A6AD00055489 AS DateTime), N'webmaster@mysite.org', N'MyURL3', 3000, 3000)

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701033, CAST(0x0000A6AD00055768 AS DateTime), N'webmaster@mysite.org', N'MyURL2', 1024, 1024)

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701034, CAST(0x0000A6AD00055771 AS DateTime), N'webmaster@mysite.org', N'MyURL1', 450, 450)

INSERT [dbo].[tblImageSuggestions] ([CounterID], [CreatedDateTime], [EmailAddress], [ImageOriginalURL], [ImageOriginalWidthPixels], [ImageOriginalHeightPixels]) 
VALUES (701035, CAST(0x0000A6AD0005577A AS DateTime), N'webmaster@mysite.org', N'MyURL4', 768, 768)

SET IDENTITY_INSERT [dbo].[tblImageSuggestions] OFF

1 个答案:

答案 0 :(得分:2)

;with cte as (
    Select *,RowNr=Row_Number() over (Partition By ImageOriginalURL Order by ImageOriginalWidthPixels*ImageOriginalHeightPixels Desc)
     From  [tblImageSuggestions]
)
--Delete From cte Where RowNr>1    
Select * from cte Where RowNr>1  -- To be deleted ... Remove if Satisfied