简体   繁体   中英

How to write SQL query to fetch the first record (latest) using IN clause?

I have an excel file with some data in it (ids) and these id's have more than one record in the database. There are around 400 ids I have and I need to get the latest record for every id. I don't want to do it one by one. I tried using IN clause but it didn't work.

Select *
from myTable with (nolock)
where submission_number IN ('02597', '69875')
order by timestame DESC;

Above query doesn't work what I want. Can some please help/guide?

Thanks

I would do this using apply :

select t.*
from (values ('02597'), ('69875')) v(submission_number) cross apply
     (select top (1) t.*
      from mytable t
      where t.submission_number = v.submission_number
      order by t.timestamp desc
     ) t;

One nice feature is that you can use outer apply , which will return a row in the result set even when there is no match in your table.

Another method that doesn't use a subquery is;

select top (1) with ties t.*
from myTable t
where submission_number in ('02597', '69875')
order by row_number() over (partition by submission_number order by timestame desc);

You can use row_number for that:

select * 
from (
    select *, row_number() over (partition by submission_number order by timestame desc) rn
    from yourtable
) t
where rn = 1

This will return a single record for each submission_number . If you only want the 2 in your in clause, you can add that back as where criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM