Finding duplicate values in a SQL table

后端 未结 30 4016
南旧
南旧 2020-11-21 13:18

It\'s easy to find duplicates with one field:

SELECT name, COUNT(email) 
FROM users
GROUP BY email
HAVING COUNT(email) > 1

So if we have

30条回答
  •  不知归路
    2020-11-21 13:47

    We can use having here which work on aggregate functions as shown below

    create table #TableB (id_account int, data int, [date] date)
    insert into #TableB values (1 ,-50, '10/20/2018'),
    (1, 20, '10/09/2018'),
    (2 ,-900, '10/01/2018'),
    (1 ,20, '09/25/2018'),
    (1 ,-100, '08/01/2018')  
    
    SELECT id_account , data, COUNT(*)
    FROM #TableB
    GROUP BY id_account , data
    HAVING COUNT(id_account) > 1
    
    drop table #TableB
    

    Here as two fields id_account and data are used with Count(*). So, it will give all the records which has more than one times same values in both columns.

    We some reason mistakely we had missed to add any constraints in SQL server table and the records has been inserted duplicate in all columns with front-end application. Then we can use below query to delete duplicate query from table.

    SELECT DISTINCT * INTO #TemNewTable FROM #OriginalTable
    TRUNCATE TABLE #OriginalTable
    INSERT INTO #OriginalTable SELECT * FROM #TemNewTable
    DROP TABLE #TemNewTable
    

    Here we have taken all the distinct records of the orignal table and deleted the records of original table. Again we inserted all the distinct values from new table to the original table and then deleted new table.

提交回复
热议问题