Search code examples
c#sqldatabaseoledb

selecting last record from table


I am deveoping a c# app in which oledb connection is used.

My table is following

payment

Id   RemFee
1     2000
2     2500
1     1500
3     8000
3     5000
2      500
3        0

I want to select and check only last record of each Id and compare Remfee to 0. If it is greater than 0 then print the record. i.e. My expected result is:

Id  
1    
2     

In this check is made for Id 1 with RemFee 1500 (as it is last record with Id1). It is grater than 0 hence record is printed.


Solution

  • Guessing you are using MSQ SQL Server and no row to know wich is your last inserted row. Try this code:

    SELECT Id, Min(RemFee) AS RemFee
      FROM payment
     WHERE RemFee > 0
     GROUP BY ID
    

    Here is an SQL Fiddle working code sample

    EDIT

    If you only want the ID field here is one option, together with the SQL Fiddle code

    SELECT myTable.Id
      FROM (SELECT Id as ID, Min(RemFee) AS Remfee
              FROM payment
             WHERE RemFee > 0
             GROUP BY ID
            ) myTable