Getting the last record in SQL in WHERE condition

后端 未结 9 2305
借酒劲吻你
借酒劲吻你 2021-02-15 04:24

i have loanTable that contain two field loan_id and status

loan_id status
==============
1       0
2       9
1       6
         


        
9条回答
  •  旧时难觅i
    2021-02-15 04:29

    Hi if this has not been solved yet. To get the last record for any field from a table the easiest way would be to add an ID to each record say pID. Also say that in your table you would like to hhet the last record for each 'Name', run the simple query

    SELECT Name, MAX(pID) as LastID
    INTO [TableName]
    FROM [YourTableName]
    GROUP BY [Name]/[Any other field you would like your last records to appear by]    
    

    You should now have a table containing the Names in one column and the last available ID for that Name. Now you can use a join to get the other details from your primary table, say this is some price or date then run the following:

    SELECT a.*,b.Price/b.date/b.[Whatever other field you want]
    FROM [TableName] a LEFT JOIN [YourTableName] 
    ON a.Name = b.Name and a.LastID = b.pID
    

    This should then give you the last records for each Name, for the first record run the same queries as above just replace the Max by Min above.

    This should be easy to follow and should run quicker as well

提交回复
热议问题