Thursday, January 5, 2017

SQL Server -How to delete the duplicate records

SET NOCOUNT ON-- Suppress data loading messages

-- Create Table
CREATE TABLE Customers (ID integer, CustName varchar(20), Pincode int)

-- Load Sample Data in Table
INSERT INTO  Customers VALUES (1, 'Jack',45454 )
INSERT INTO  Customers VALUES (2, 'Jill', 43453)
INSERT INTO  Customers VALUES (3, 'Tom', 43453)
INSERT INTO  Customers VALUES (4, 'Kathy', 22343)
INSERT INTO  Customers VALUES (5, 'David', 65443)
INSERT INTO  Customers VALUES (6, 'Kathy', 22343)
INSERT INTO  Customers VALUES (7, 'Kim', 65443)
INSERT INTO  Customers VALUES (8, 'Hoggart', 33443)
INSERT INTO  Customers VALUES (9, 'Kate', 61143)
INSERT INTO  Customers VALUES (10, 'Kim', 65443)
go
select * from Customers
go
select MAX(id) as ID,custname,pincode from Customers
group by CustName,Pincode
having COUNT(*)>1
---delete duplicate rows
begin tran
delete from Customers where ID in
(select max(id) from Customers
group by CustName,Pincode having COUNT(*)>1)
go
select * from customers
rollback tran
INSERT INTO Customers VALUES (11, 'Kim', 65443)
go
DELETE FROM Customers
WHERE EXISTS (
SELECT NULL
FROM Customers c2
WHERE Customers.CustName = c2.CustName
AND Customers.Pincode = c2.Pincode
AND Customers.ID > c2.Id
)

No comments:

Search This Blog

DAX - Grouping on multiple columns and the count

Please go thorugh the below URL for entire soultion. http://community.powerbi.com/t5/Desktop/DAX-Grouping-on-multiple-columns-and-the-cou...