V
V
Victor P.2021-04-21 11:45:54
SQL Server
Victor P., 2021-04-21 11:45:54

How to leave only the last row in sql?

MS SQL
There is a journal, a flat table:
Id (PK)
ForeignKey
Datetime
Text

It is necessary to leave one record for each ForeignKey, which has a maximum date, and delete the rest.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-04-21
@Jeer

You can use ROW_NUMBER:

SELECT Id, ForeignKey, Datetime, Text FROM (
  SELECT
    ROW_NUMBER() OVER(PARTITION BY ForeignKey ORDER BY DateTime DESC) as rn,
    *
  FROM table
  WHERE
    rn = 1
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question