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.
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:
from - first day of month (2020-10-01);
to - last day of month (2020-10-31);
? 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);
Related
I want to query last 24h in my database SQLite. I have 2 rows time example (18:04:56) and date (2020-12-06 ). When I use this query
SELECT name,cdate,ctime, * FROM {table} WHERE cdate >= datetime('now','-1 day') ORDER BY id DESC
I got only last queries in the same day. (LAST QUERY 00:00:46)
How deal with it ?
You should create a datetime value from cdate and ctime to compare with DATETIME('now','-1 day'):
SELECT name, cdate, ctime
FROM {table}
WHERE (cdate || ' ' || ctime) >= DATETIME('now','-1 day')
ORDER BY id DESC
i m trying like this:
char *Query = "DELETE FROM tablename WHERE starttime < NOW() - INTERVAL 1 DAY";
First,to delete last 2 days,you need to check data greater than the specified date,then you need to use DATE('now', '-1 days') to get the date,more details can be found at How to structure my query in sqlite?
DELETE FROM bandwidthmaster WHERE starttime > DATE('now', '-1 days');
I want to put filter on an Informix query:
WHERE agentstatedetail.eventdatetime < '1753-01-01 00:00:00' - INTERVAL(3) DAY TO DAY
but it fails ...
Please tell where it goes wrong.
As noted in a comment, the solution is to ensure that the string is interpreted as a DATETIME value. The simple way to do that is to use the DATETIME literal notation:
DATETIME(1753-01-01 00:00:00) YEAR TO SECOND
To demonstrate:
CREATE TABLE agentstatedetail
(
eventdatetime DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY,
eventname VARCHAR(64) NOT NULL
);
INSERT INTO agentstatedetail VALUES('1752-12-25 12:00:00', 'Christmas Day, Noon, 1752');
INSERT INTO agentstatedetail VALUES('1752-12-31 12:00:00', 'New Year''s Eve, Noon, 1752');
INSERT INTO agentstatedetail VALUES('1753-01-01 12:00:00', 'New Year''s Day, Noon, 1753');
SELECT * FROM agentstatedetail WHERE agentstatedetail.eventdatetime < '1753-01-01 00:00:00' - INTERVAL(3) DAY TO DAY;
This is your original WHERE clause embedded into a minimal SELECT statement. It yields the error:
SQL -1261: Too many digits in the first field of datetime or interval.
(NB: It would have been helpful to include the error message in the question.)
Here's an alternative version of the query, with the DATETIME literal in place:
SELECT * FROM agentstatedetail
WHERE agentstatedetail.eventdatetime < DATETIME(1753-01-01 00:00:00) YEAR TO SECOND -
INTERVAL(3) DAY TO DAY
;
Output from the sample data:
1752-12-25 12:00:00|Christmas DAY, Noon, 1752
I observe that the value calculated is a constant; you could rewrite the code as:
SELECT * FROM agentstatedetail
WHERE agentstatedetail.eventdatetime < DATETIME(1752-12-29 00:00:00) YEAR TO SECOND
I suspect that the value is passed as a parameter somewhere along the line.
Alternatively, you can cast the string to a DATETIME value and you'd get the same result:
SELECT * FROM agentstatedetail
WHERE agentstatedetail.eventdatetime < CAST('1753-01-01 00:00:00' AS DATETIME YEAR TO SECOND) -
INTERVAL(3) DAY TO DAY
;
or:
SELECT * FROM agentstatedetail
WHERE agentstatedetail.eventdatetime < '1753-01-01 00:00:00'::DATETIME YEAR TO SECOND -
INTERVAL(3) DAY TO DAY
In my SQlite table, it has DateTime field example : order_date
How to perform these tasks:
Retrieve records by Month like Jan, Feb, Mar and so on in Year 2013.
Retrieve records by Begin date and End Date with criteria like above(1)
Thanks
How to convert `DateTime` for format requires by SQLite for (1) and (2)
DateTime Dt = new DateTime.Today();
Month-year ? Year?
Records = await db.QueryAsync("Select * From Purchase where order_date=" + "Month-Year");
In SQLite , which operator is correct : `=` or `==`?
----- Update:
using SQlite:strftime
SELECT * FROM tablename WHERE strftime('%Y', Order_Date) = '2013' AND strftime('%m', Order_Date) = '2';
1) Is there a function to get month as number from DateTime?
I assume you are using sqlite-net.
As such you may use parameters in your query:
//Returning all records from February 2013
Records = await db.QueryAsync<Purchase>("Select * From Purchase where order_date >= ? and order_date < ?", new DateTime(2013, 2, 1), new DateTime(2013, 3, 1));
Right now I'm doing this:
SELECT * FROM messages WHERE location_id = 7 AND date(date) <= date('now', 'localtime') ORDER BY date,revision LIMIT 1
This gives me the most recent message, with the highest revision #.
How can retrieve all of the most recent messages? If I do:
SELECT * FROM messages WHERE date(date) <= date('now', 'localtime') ORDER BY date,revision
I still get messages with lower revision numbers.
SELECT * FROM messages m1
WHERE date(date) <= date('now', 'localtime')
and revision = (select max(revision) from messages m2 where date(m2.date) = date(m1.date))
and location_id = 7
ORDER BY date,revision
Here's a query that finds the most recent revision per location:
SELECT m1.* FROM messages m1
LEFT OUTER JOIN messages m2
ON (m1.location_id = m2.location_id AND m1.revision < m2.revision)
WHERE m2.location_id IS NULL
ORDER BY date, revision;