How to Select by month and year in SQLite - sqlite

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));

Related

How to get data month wise sqflite in Flutter?

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);

I inserted rows with the UTC date into an int column in my database. How can I get just the rows that were inserted in the last 24 hours?

Here's the insert that I used:
db2.Insert(new QuizHistory()
{
QuizId = quiz,
Cards = 0,
Points = points,
UtcNow = (int)Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds),
Viewed = 1,
Deck = deck
});
I tried looking at the different sql functions but now I am more confused than ever.
select * QuizHistory << but just for the last 24 hours.
As you are storing the date as seconds since january 1, 1970, a solution would be to use strftime :
select *
from QuizHistory
where UtcNow > strftime('%s', 'now', '-1 day')
i.e. with %s as format (seconds since 1970-01-01), for the now date with a -1 day modifier

Return 0 if the date for a certain day does not have values

I'm doing a query to return the number of count records for a certain date.
The problem is when I use the GroupBy by a certain day, If the date have no records then the date for that day will not be shown in the output.
How can I achieve that?
I'm doing something like:
SELECT COUNT(History.Id)
FROM History
INNER JOIN User ON User.Id = History.UserId
WHERE (#StartDate = #NullDate OR History.CreatedOnDate >= #StartDate)
AND (#EndDate = #NullDate OR History.CreatedOnDate <= #EndDate)
GROUP BY History.CreatedOnDat
Example
01-08, 3 records
02-08, 2 records
04-08, 5 records
I need to have 03-08 with 0 records.
Create a temp table with one day per row:
Declare #StartDate datetime = '2016-08-01'
Declare #EndDate datetime = '2016-08-31'
declare #temp table
(
oneday datetime
);
WHILE #StartDate <= #EndDate
begin
INSERT INTO #temp VALUES (#StartDate);
SET #StartDate = Dateadd(Day,1, #StartDate);
end
select * from #temp
Then, simply join your query with this temp table.

Select weekend or weekday data from a table based on date param

How can I select data from a table based on weekday or weekend, like
if date is a weekday then select only historical weekday data from the table &
if date is a weekend then select only historical weekend data.
I have tried to do that in this way but no luck
DECLARE #MyDate DATE = '08/17/2013'
SELECT datename(dw,#MyDate)
SELECT * FROM MyTable
WHERE
datename(dw,DateColumnInTable) IN (
CASE WHEN (datename(dw,#MyDate) IN ('Saturday','Sunday')) THEN '''Saturday'',''Sunday'''
ELSE 'Monday'',''Tuesday'',''Wednesday'',''Thursday'',''Friday'
END )
Any I can see lots of data in my table for saturday and sunday but this query is giving me blank record set.
Here's one way:
DECLARE #MyDate DATE = '08/17/2013'
IF (DATEPART(weekday, #MyDate) IN (1,7))
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) IN (1,7)
ELSE
SELECT *
FROM MyTable
WHERE DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6
If you would like to do it in one clause you can do something like the following, but it may perform worse:
SELECT *
FROM MyTable
WHERE (DATEPART(weekday, #MyDate) IN (1,7) AND DATEPART(weekday, DateColumnInTable) IN (1,7))
OR (DATEPART(weekday, #MyDate) BETWEEN 2 AND 6 AND DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6)

Using query to retrieve records which their createdate is a special date?

I have a table that has four columns.
One of them is named "CreateDate" and it's datatype is "DateTime".
Now, what would be a true T-SQL which retrieves records that their CreateDate is for example
"2010-02-10" ?
If you wish to select all records with CreateDate on a specific date you could use something like
SELECT *
FROM YourTable
WHERE DATEADD(dd, DATEDIFF(dd,0,CreateDate), 0) = '2010-02-10'
or
DECLARE #Date DATETIME
SELECT #Date = '01 Feb 2010'
SELECT *
FROM YourTable
WHERE CreateDate >= #Date
AND CreateDate < #Date + 1
EDIT
If you wish to change the display format of the date, from SQL Server Date Formats
You could try
DECLARE #YourTable TABLE(
CreateDate DATETIME
)
INSERT INTO #YourTable SELECT '01 Feb 2010'
INSERT INTO #YourTable SELECT GETDATE()
SELECT *,
CONVERT(VARCHAR(10), CreateDate, 120) DateValue
FROM #YourTable

Resources