Search code examples
androiddatabasesqliteandroid-sqlite

Retrieve date wise data from sql database in android


I want to compare current month data(expenses) with previous month data(expenses) which is store in database datewise. kindly some one guide me please.

I write this command for current month data but did not work for me.

Cursor

cursor= database.rawQuery(" 
SELECT  amount 
  FROM Groceryitems 
 WHERE Strftime('%Y-%m', 'now') 
", new String[]{});

Solution

  • There must be a date column in the table Groceryitems and this column you must check if it contains a date of the current month:

    String sql = "SELECT amount FROM Groceryitems WHERE strftime('%Y-%m', datecolumn) = strftime('%Y-%m', 'now')";
    cursor= database.rawQuery(sql, null);
    

    Change datecolumn with the name of the date column in the table.
    To get the previous month's data:

    String sql = "SELECT amount FROM Groceryitems WHERE strftime('%Y-%m', datecolumn) = strftime('%Y-%m', 'now', '-1 month')";
    cursor= database.rawQuery(sql, null);