SQL Server Delete unecessary time from selected early of time [duplicate]

bjg7j2ky  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(108)

This question already has answers here:

Delete all records except the most recent one? (3 answers)
Closed 12 days ago.

I've a table from SQL Server and I've managed to tidy up the data. How to make unselected time or delete the past time data. so just need early time. So I use this query:

SELECT table1.id, table1.name,MIN(time)
FROM table1 
GROUP BY id, name,time

and I'm failing when I try query like this:

DELETE FROM table1
WHERE table1.date EXCEPT MIN(time)

this is my table:

Id_student  name    date
1   azhar       06:19:20  
1   azhar       06:30:30  
1   azhar       06:39:30  
1   azhar       06:40:30  
1   azhar       06:49:30

and this is expected finished table:

Id_student  name    date
1   azhar   06:19:20

expected table

oipij1gg

oipij1gg1#

You can first use your query that fetches the earliest time per id as subquery and then in a second step delete all other rows. Something like this:

WITH earliest AS
  (SELECT id, MIN(time) AS eTime
  FROM table1 
    GROUP BY id)
DELETE FROM table1 
  WHERE NOT EXISTS 
    (SELECT 1 FROM earliest WHERE id = table1.id AND table1.time = eTime);

See this fiddle . It shows this will work correctly.

相关问题