Getting the last record in SQL in WHERE condition

后端 未结 9 2253
借酒劲吻你
借酒劲吻你 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.

    0 讨论(0)
  • 2021-02-15 04:51

    Use a data reader. When it exits the while loop it will be on the last row. As the other posters stated unless you put a sort on the query, the row order could change. Even if there is a clustered index on the table it might not return the rows in that order (without a sort on the clustered index).

        SqlDataReader rdr = SQLcmd.ExecuteReader();
        while (rdr.Read())
        {
        }
        string lastVal = rdr[0].ToString()
        rdr.Close();
    

    You could also use a ROW_NUMBER() but that requires a sort and you cannot use ROW_NUMBER() directly in the Where. But you can fool it by creating a derived table. The rdr solution above is faster.

    0 讨论(0)
  • 2021-02-15 04:54

    I think this code may help you:

    WITH cte_Loans
    AS
    (
    SELECT   LoanID
            ,[Status]
            ,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN
    FROM    LoanTable
    )
    
    SELECT   LoanID
            ,[Status]
    FROM    LoanTable L1
    WHERE   RN = (  SELECT max(RN)
                    FROM LoanTable L2
                    WHERE L2.LoanID = L1.LoanID)
    
    0 讨论(0)
提交回复
热议问题