问题
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