简体   繁体   中英

How to pick the most recent record from sql table among multiple records?

I have developed a website which facilitates a LAWYER to enter CASE DETAILS along with NEXT HEARING DATES . Each case can have more than 1 HEARING DATES . Let's assume we have 3 CASES in table with each having multiple hearing dates but I want to pick most last HEARING DATE of each case then how I should go for it ?

I have used TOP then MAX with select statement but nothing worked.

What I am stroing are:

pk_Cases_CaseID
CaseNo
CaseTitle
CaseRemarks
CaseNextHearingDate
IsCaseFinalized
CaseEntryDateTime

In SQL Server, the typical method would be to use row_number() . Your question doesn't really explain what the data layout is (the column names seem quite different from the description). However, the logic looks like:

select h.*
from (select h.*,
             row_number() over (partition by caseno order by hearingdate desc) as seqnum
      from hearings h
     ) h
where seqnum = 1;

Based on your comment on using Top and Max, I'm assuming you might be missing some grouping logic. This is assuming the CaseNo is the same for the different rows.

  select 
         CaseNo, Max(CaseNextHearingDate)
  from 
         CaseTable
  GROUP BY 
         CaseNo

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