Find and Remove Duplicate Rows from a SQL Server Table

此生再无相见时 提交于 2020-04-17 20:49:46

问题


I'm using a SQL Server database and I have a datetime column datatype is datetime. Some rows under datetime column are duplicate, how can I delete the duplicate row and sort table by datetime?

T-SQL:

SELECT
    [datetime]
FROM [database].[dbo].[data]

Result:

datetime
2020-03-18 09:18:00.000
2020-03-18 09:19:00.000
2020-03-18 09:20:00.000
.............
.............
.............
2020-03-18 09:19:00.000
2020-03-18 09:20:00.000

Can anyone help?


回答1:


If I understand correctly, you just want:

SELECT DISTINCT [datetime]
FROM [database].[dbo].[data]
ORDER BY [datetime];

Note: datetime is a bad name for a column because it is the name of a type in SQL Server.

If you actually want to delete the rows, then use;

with todelete as (
      select d.*,
             row_number() over (partition by [datetime] order by [datetime]) as seqnum
      from [database].[dbo].[data]
     )
delete from todelete
    where seqnum > 1;

SQL tables represent unordered sets. So, if you want to see the results in a particular order you need an order by in the query, as in the first example.



来源:https://stackoverflow.com/questions/60868459/find-and-remove-duplicate-rows-from-a-sql-server-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!