How to select current dates from current month - c#

I would like to retrieve the data between 1 -30 of the current month [ i am using MSACCESS Dbase to do so] Below is the query that i am trying --
SELECT count(usercategory) as category_count ,usercategory FROM user_category
where IssueDate between DATEADD('m', DATEDIFF('m', 0, DATE()) - 0 , 0) and DATEADD('m', DATEDIFF('m', 0, DATE()) + 1, - 1 ) group by usercategory
Data that i am holding in my MSACCESS Dbase -
Category1 9/7/2013 12:00:00 AM
Category1 9/8/2013 12:00:00 AM
Category2 10/8/2013 12:00:00 AM
so output should have only 2 records
but my query is giving no results

Here is the query I think you need. All the functions it uses are always available in Access SQL regardless of whether the query is run from within an Access session or from without (as in your c# situation).
The db engine will evaluate both those DateSerial expressions once, then use their results to filter the result set. This approach will be especially fast with an index on IssueDate.
SELECT
Count(usercategory) AS category_count,
usercategory
FROM user_category
WHERE
IssueDate >= DateSerial(Year(Date()), Month(Date()), 1)
AND IssueDate < DateSerial(Year(Date()), Month(Date()) + 1, 0)
GROUP BY usercategory;
Here is an Access Immediate window session which explains the logic for those DateSerial expressions ...
? Date()
9/6/2013
? Year(Date())
2013
? Month(Date())
9
' get the date for first of this month ...
? DateSerial(Year(Date()), Month(Date()), 1)
9/1/2013
' now get the date for the last of this month ...
? DateSerial(Year(Date()), Month(Date()) + 1, 0)
9/30/2013

Related

SQLite-net-pcl Comparing Dates

As stated in the question I am attempting to do a date comparison for tasks that are done within a specific date range.
My model has a boolean called "Done" and a string that stores dates of completion called "DatesCompleted"
I currently have a query on that shows me all Done items limited to 25 and it works just fine:
return db.QueryAsync<Tasks>("SELECT * FROM [Tasks] WHERE [Done] = 1 LIMIT 25");
How can I get only dates completed that are 7 days prior to today? This is kind of sudo code how I'd expect to get the solution but I don't know how to write it out in SQLite-net-pcl,
return db.QueryAsync<Tasks>("SELECT * FROM [Tasks] WHERE [Done] = 1 AND [DatesCompleted] >= (DateTime.Now - new TimeSpan(7,0,0,0))` LIMIT 25");
Edit:
After attempting the first solution I am having no luck, all items regardless of completion time appear to show up. I tried this:
foreach(var ii in TaskListDoneSource)
{
System.Diagnostics.Debug.WriteLine(ii.Name + " completed on : " + ii.DateCompleted + " compared against " + (DateTime.Now-new TimeSpan(7,0,0,0)).ToString());
if (ii.DateCompleted > (DateTime.Now - new TimeSpan(7, 0, 0, 0)))
System.Diagnostics.Debug.WriteLine("The date completed has not quite hit 7 days");
}
The IF statement shows me that it is working when I am within 7 days but outside obviously no IF statement call. So that tells me I'm doing something wrong with the query recommended in first answer:
SELECT * FROM [Tasks] WHERE [Done] = 1 AND [DateCompleted] >=
datetime('now', '-7 day')
EDIT 2: I got it working with that query provided. Only thing that was off was off was having the DateCompleted as a DateTime instead of a string that was formatted properly in my model. (https://www.sqlite.org/lang_datefunc.html)
Assuming that in [DatesCompleted] you store timestamps in ISO format YYYY-MM-DD hh:mm:ss, the correct SQLite syntax to get a timestamp exactly 7 days before the current timestamp is:
datetime('now', '-7 day')
or:
datetime('now', '-7 day', 'localtime')
to get the timestamp in local time.
so your query should be:
SELECT *
FROM [Tasks]
WHERE [Done] = 1 AND [DatesCompleted] >= datetime('now', '-7 day')

how to find date range between two dates in days format using linq c#

I have a requirement for generating report in form of 15 days,30 days,45 days.
I have to compare the list data which is coming from db with current date.example if difference is 5days. It is less than 15,so i should send to 15 days ,if >15 i should send to greater than 15etc.How to write linq query for this.can any one help on this please
I'm not sure that can be possible to make this in only one query.
But, I can propose you another solution.
Instead of one query, you can use one query for every case.
In order to compare date difference, you can use SqlFunctions Class.
For this, you should use :
using System.Data.Objects.SqlClient;
Here is the query for 5 days with an imaginary table and fields :
var lstDiff5 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) <= 5
select ro).ToList();
The DateDiff Function takes the date part (DD for days), the start date and the end date. In my case the start date is the current date.
And for 15 days :
var lstDiff15 = (from ro in dc.Commandes where
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) > 5 &&
SqlFunctions.DateDiff("DD", ro.Cmd_PromisDate, DateTime.Now) >= 15
select ro).ToList();
You can change the operators > et >= depending your need.
At the end, you can fill your report using all of your lists or you can merge your lists into a new list in order to bind your report to your final list.
You can use DaysBetween function in linq.It will return all dates betwee the given dates.
Example:
DateTime dt = DateTime.Today.Date.AddMonths(1);
int d = dt.DaysBetween(DateTime.Today).ToList().Count;

C# sequence number issue in database

I have a column in the database table i.e. transaction Id. Its data type is var char(50). Now I want to save a row by combining the current date with a sequential number generated.
For Example 10/9/2016 is the date so first transaction is saved like 10920161 and the next one like 10920162 and so on. The sequential number is reset to 1 after every day.
How can I do this?
In SQL Server, it can be as simple as:
transactionId =
CONCAT(DATEPART(MONTH, GETDATE()),
DATEPART(DAY, GETDATE()),
DATEPART(YEAR, GETDATE()),
(SELECT COUNT(1)
FROM tableName
WHERE CONVERT(DATE, dateColumn) = CONVERT(DATE, getdate())) + 1)
Get the Number of transactions for that date, and add one to it. Concat that with a formatted string of Today's Date.
If you already have 3 records for today's date, the result would be:
100920164
Running SQL-Fiddle
Edit: EF suggested snippet:
string dateStr = DateTime.Today.ToString("Mdyyyy");
DateTime todayMidnight = DateTime.Today;
DateTime tomorrowMidnight = DateTime.Today.AddDays(1);
obj.transactionId = dateStr +
context.tableName.Count(x=> x.dateColumn >= todayMidnight
&& x.dateColumn < tomorrowMidnight) + 1;

How to select a data access database filtering with the months of the date?

I want to select the row of a database when the month of a date is accurate. for the year I did it:
select * from table where YEAR(date)='2015' it works well for the years
for the months I made :
select * from table where Month(date)='01'// I have the date format dd/mm/yyyy
thanks
From MONTH FUNCTION;
The Microsoft Access Month function returns the month (a number from 1
to 12) given a date value.
You should check it with an integer, not a string like;
select * from table where Month(date) = 1
Try this
select * from table where Month(date)='01' and YEAR(date)='2015'

SQLite date comparison on non-valid Timestring formats

I want to get entries from a SQLite database by date.
SQLite valid timestring formats are listed here as:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDD.DDDD
I have another format in the database that is D/M/YYYY
Is there a way to compare dates in this database (and select entries accordingly) without having to select, parse and compare all the DateTime objects from all rows in the table?
you can compare dates in SQLITE by using some conventons
try to save dates in the same Format
SQLITE uses 3 Dateformats (not realy Formats but used ones)
* String as mentioned (YYYY-MM-DD [HH:MI:SS])
* Integer
* Real
I mostly use real for date-fields which are used for comparing
They have to be saved by the julianday() Function
The biggest Problem is, SQLITE has only a small date Converter function, so not well-formed dates can't or will not be correctly converted
Sqlite doesn't support comparing dates (and datetimes) specifically "out of the box".
As far as I know, you have three options (in order of my preference):
Use a format that is suited for string-based comparisons (e.g. YYYYMMDD). Here is something to get you started:
sqlite> create table foo (d TEXT);
sqlite> insert into foo values ('02/01/2012');
sqlite> select substr(d, 7, 4) || substr(d, 1, 2) || substr(d, 4, 2) from foo;
20120201
Use convoluted SQL to get it done using "out of the box" functions.
Create a function yourself.
I made a really FAST query and I am proud of it :p. So here it is:
public static string FromClausePartForDateComparisson(string tableName, string dateFieldName, string idFieldName, DateTime from, DateTime to)
{
string clause = string.Format(#" from
(SELECT {0} as filteredId,
Substr('00'|| -- make day with two digits
CASE Substr({1}.{2}, 3, 1)
WHEN '/' THEN Substr({1}.{2}, 1, 2)
ELSE Substr({1}.{2}, 1, 1)
END, -2, 2) AS DAY,
Substr('00'|| -- make month with two digits
CASE Length({1}.{2})
WHEN 8 THEN Substr({1}.{2}, 3, 1)
WHEN 9 THEN CASE Substr({1}.{2}, 3, 1)
WHEN '/' THEN Substr({1}.{2}, 4, 1)
ELSE Substr({1}.{2}, 3, 2)
END
WHEN 10 THEN Substr({1}.{2}, 4, 2)
END, -2, 2) AS MONTH,
Substr({1}.{2}, Length({1}.{2}) - 3, 4) AS YEAR
FROM {1}
WHERE Strftime('%Y%m%d', YEAR||'-'||MONTH||'-'|| DAY) BETWEEN
Strftime('%Y%m%d', '{3}') AND
Strftime('%Y%m%d', '{4}')) AS filteredtable
INNER JOIN {1} ON filteredtable.filteredId = {1}.{0} ", idFieldName, tableName, dateFieldName, from.ToString("yyyy-MM-dd"), to.ToString("yyyy-MM-dd"));
return clause;
}
And it is being used as:
var selectCommand = new SQLiteCommand("SELECT * " +
FromClausePartForDateComparisson("TABLENAME", "DATE", "ID", from, to) +
#"WHERE ID_TABLENAME=#Id";

Categories