Orders テーブルに基づく Northwind の例を次に示します。
(EmployeeID , ShipCity , ShipCountry) 列に基づく重複があります。
これらの 2 行の間のコードのみを実行する場合:
/* Run everything below this line to show crux of the fix */
/* Run everything above this line to show crux of the fix */
それがどのように機能するかがわかります。基本的:
(1) 対象の 3 つの列に対して GROUP BY を実行します。 (派生1重複)
(2) 次に、これらの 3 つの列を使用してテーブルに結合します。(ords.EmployeeID =派生1Duplicates.従業員IDおよびords.ShipCity =派生1Duplicates.ShipCityおよびords.ShipCountry =派生1Duplicates.ShipCountry)
(3) 次に、グループごとに基数 (1、2、3、4 など) でタグ付けします ( ROW_NUMBER() を使用) 。
(4) 次に、基数が「1」の各グループの行を保持します。(ここで、派生2DuplicatedEliminated.RowIDByGroupBy = 1)
Use Northwind
GO
declare @DestinationVariableTable table (
NotNeededButForFunRowIDByGroupBy int not null ,
NotNeededButForFunDuplicateCount int not null ,
[OrderID] [int] NOT NULL,
[CustomerID] [nchar](5) NULL,
[EmployeeID] [int] NULL,
[OrderDate] [datetime] NULL,
[RequiredDate] [datetime] NULL,
[ShippedDate] [datetime] NULL,
[ShipVia] [int] NULL,
[Freight] [money] NULL,
[ShipName] [nvarchar](40) NULL,
[ShipAddress] [nvarchar](60) NULL,
[ShipCity] [nvarchar](15) NULL,
[ShipRegion] [nvarchar](15) NULL,
[ShipPostalCode] [nvarchar](10) NULL,
[ShipCountry] [nvarchar](15) NULL
)
INSERT INTO @DestinationVariableTable (NotNeededButForFunRowIDByGroupBy , NotNeededButForFunDuplicateCount , OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry )
Select RowIDByGroupBy , MyDuplicateCount , OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry
From
(
/* Run everything below this line to show crux of the fix */
Select
RowIDByGroupBy = ROW_NUMBER() OVER(PARTITION BY ords.EmployeeID , ords.ShipCity , ords.ShipCountry ORDER BY ords.OrderID )
, derived1Duplicates.MyDuplicateCount
, ords.*
from
[dbo].[Orders] ords
join
(
select EmployeeID , ShipCity , ShipCountry , COUNT(*) as MyDuplicateCount from [dbo].[Orders] GROUP BY EmployeeID , ShipCity , ShipCountry /*HAVING COUNT(*) > 1*/
) as derived1Duplicates
on ords.EmployeeID = derived1Duplicates.EmployeeID and ords.ShipCity = derived1Duplicates.ShipCity and ords.ShipCountry = derived1Duplicates.ShipCountry
/* Run everything above this line to show crux of the fix */
)
as derived2DuplicatedEliminated
where derived2DuplicatedEliminated.RowIDByGroupBy = 1
select * from @DestinationVariableTable
強調されたテキスト*強調されたテキスト*強調されたテキスト