Getting the last record in SQL in WHERE condition

后端 未结 9 2282
借酒劲吻你
借酒劲吻你 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条回答
  •  长发绾君心
    2021-02-15 04:46

    If you don't have any identifying columns you could use to get the insert order. You can always do it like this. But it's hacky, and not very pretty.

    select
    t.row1,
    t.row2,
    ROW_NUMBER() OVER (ORDER BY t.[count]) AS rownum from (
    select 
        tab.row1,
        tab.row2,
        1 as [count] 
    from table tab) t
    

    So basically you get the 'natural order' if you can call it that, and add some column with all the same data. This can be used to sort by the 'natural order', giving you an opportunity to place a row number column on the next query.

    Personally, if the system you are using hasn't got a time stamp/identity column, and the current users are using the 'natural order', I would quickly add a column and use this query to create some sort of time stamp/incremental key. Rather than risking having some automation mechanism change the 'natural order', breaking the data needed.

提交回复
热议问题