2
votes

Image for how does data look I am making an expense tracker app using flutter, I want to show the sum of expenses done by the user every month for example:

Month              Amount Spended
January              2000
February             1600

Database columns:
"CREATE TABLE $TABLE_EXPENSES ("
      "$COLUMN_ID INTEGER PRIMARY KEY,"
      "$COLUMN_NAME TEXT,"
      "$COLUMN_AMOUNT TEXT,"
      "$COLUMN_UNNECESSARYEXPENSES INTEGER,"
      "$COLUMN_CATEGORY TEXT,"
      "$COLUMN_DATETIME TEXT"
      ")",

I am using sqflite to create a database and I am storing data as text. I want to retrieve expenses of every day in a month and then sum up the expenses of every day and show it in ListTile

Edit:

Query: 'SELECT * SUM(COLUMN_AMOUNT) FROM TABLE_EXPENSES WHERE COLUMN_DATETIME >= ? AND COLUMN_DATETIME <= ?'

This is the error that I am getting (for query):

E/SQLiteLog(10318): (1) near "SELECT": syntax error
E/flutter (10318): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: DatabaseException(near "SELECT": syntax error (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM expenses WHERE SELECT * SUM(COLUMN_AMOUNT) FROM TABLE_EXPENSES WHERE COLUMN_DATETIME >= 2019 AND COLUMN_DATETIME <= 1989) sql 'SELECT * FROM expenses WHERE SELECT * SUM(COLUMN_AMOUNT) FROM TABLE_EXPENSES WHERE COLUMN_DATETIME >= ? AND COLUMN_DATETIME <= ?' args [2019, 1989]}

Function which I am currently using:

Future getDataJan() async{
final db = await database;
sumJan= db.rawQuery(
    'SELECT SUM(AMOUNT) FROM EXPENSES WHERE DATETIME >= ? AND DATETIME <= ?',
    [2021-01-01, 2021-01-31] ).then(Sqflite.firstIntValue);
finalJan=sumJan.toString();

}

Image: errorImage

Thanks for your replies.

1
Where is the MCVE of the question? Please include it to the question. Also make sure to read How do I ask good question?Ahx
Post sample data of your table.forpas
I've added it hanksSanchay Kasturey

1 Answers

2
votes

You can operate with a date with format like yyyy-MM-dd HH:mm:SS and create requests to database for search entities between month.

Date format example:

DateFormat('yyyy-MM-dd HH:mm:SS').format(date)

Query example:

return database.query(
  tableName,
  where: 'date >= ? and date <= ?',
  whereArgs: [from, to],
)
.then((data) => data.map(_fromMap).toList());

Variables in example:

  1. from - first day of month (2020-10-01);
  2. to - last day of month (2020-10-31);
  3. ? in where - takes values from whereArgs (first ? - from, second - to);

Note: in comments describes that you should use SQFLite tooling for creating requests and do not use raw queries (for performance reasons).

Select example

final result = await database.rawQuery(
  'select * sum(COLUMN_AMOUNT) from TABLE_EXPENSES where COLUMN_DATETIME >= ? and COLUMN_DATETIME <= ?',
  [from, to],
).then(Sqflite.firstIntValue);