Hi
- User
Hi
- Assistant
Hello! How can I assist you today?
- User
I have a table with the below columns Supplier Parent Name Commodity Tower load_date load_Update_date trade_nonTrade Child Name Action OGSParentKey OGSSuppKey OGSChildKey SpcltyFlag
Table is having duplicate rows with all the columns having same values except for load_date and load_Update_date. I need to delete duplicate record and retaining record with latest 'load_date'.
Please give sql server query for the same
- Assistant
To delete duplicate records in your SQL Server table and retain the record with the latest
load_date, you can use a Common Table Expression (CTE) with theROW_NUMBER()function to identify and remove duplicates. Here's the query:WITH CTE_Duplicates AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY Supplier, ParentName, CommodityTower, trade_nonTrade, ChildName, Action, OGSParentKey, OGSSuppKey, OGSChildKey, SpcltyFlag ORDER BY load_date DESC ) AS RowNum FROM YourTableName ) DELETE FROM YourTableName WHERE ID IN ( SELECT ID FROM CTE_Duplicates WHERE RowNum > 1 ); - User
ID column is not present in the table
- Assistant
Thank you for clarifying that there is no
IDcolumn in your table. In that case, we will need to reference the duplicate rows using all columns exceptload_dateandload_Update_date. Here's the correct SQL Server query to delete duplicate rows while retaining the record with the latestload_date:WITH CTE_Duplicates AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY Supplier, ParentName, CommodityTower, trade_nonTrade, ChildName, Action, OGSParentKey, OGSSuppKey, OGSChildKey, SpcltyFlag ORDER BY load_date DESC ) AS RowNum FROM YourTableName ) DELETE FROM CTE_Duplicates WHERE RowNum > 1;Explanation:
-
ROW_NUMBER: The function assigns a unique number to each row within a group of duplicates, based on the clause. The most relevant/unique columns are included in the . The row with the gets .
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.