I have this query:
SELECT who,whenAT
FROM seen
WHERE whenAT <= Datetime('now', '-5 minutes')
DateTimes stored in whenAT are formatted like this "10/12/2011 12:33:13 AM" whenAT is a TimeStamp.
that current query returns all records for some reason.
i'm inserting the datetime from code as DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") this is what is being saved into the table "10/12/2011 12:33:13 AM" i want to get all records within the last 5 minutes. everything i have tried either returns all records or no records.
Your query should be
SELECT who,whenAT FROM seen WHERE whenAT >= Datetime('now', '-5 minutes')
To get the last 5 minute, < will get everything besides the last 5 minutes
as Fatal510 said, you need to add the modifier 'localtime'
here some reference about datetime modifier https://www.sqlite.org/lang_datefunc.html
and here some example
SELECT who,whenAT FROM seen WHERE whenAT >= Datetime('now', '-5 minutes', 'localtime')
needed to add the modifier 'localtime'
Related
I have the following LINQ to query the database and retreive deleted products from a particular date.
return _myDbEntities.Log
.Where(p => p.Action.Equals("Deleted") &&
(p.ActionDate > fromDate))
.Select(p => new DeletedProduct()
{
ProductId = p.ProductId,
ActionDate = p.ActionDate
}).ToList();
However, the query is retreiving values like product.ActionDate.Value = {12/8/2016 11:41:00 AM} when the fromDate was fromDate = {12/8/2016 11:41:00 AM}
The query clearly says GREATER THAN. What is happening here?
There are fractions of a second to each of your properties. Most likely, your record wasn't created at an exact second, whereas any user-created time would be set as such.
Another possibility is the difference between datetime and datetime2 in SQL Server.
The DateTime type stores time at much higher precision than seconds. They could be differing at millisecond or even tick (100 nanoseconds) level.
If you want to compare on a higher level, try this:
(p.ActionDate.Ticks / 10000000) > (fromDate.Ticks / 10000000)
Where 10000000 is the number of ticks in a second. Since the /is an integer division that does truncate the fraction, you turn ticks into full seconds.
UPDATE:
It seems like you are using entity framework. The comparison above will possibly not work there. The solution is to run your original query against the database, do a ToList and then filter the results again in a LINQ2Objects query using the logic above.
I have a column within my database called "Month". What i want to do is filter the table between two months. Example of this is March - June. I have code which works BUT only works alphabetically
string strquery = "select * from tbl_DR_data ";
string strq2 = "where";
if (DropDownList6.SelectedItem.Text != "All" && DropDownList8.SelectedItem.Text != "All") {
string month1 = DropDownList6.SelectedItem.Text.ToString();
string month2 = DropDownList8.SelectedItem.Text.ToString();
strq2 = strq2 + "[Month] BETWEEN'" + month1 + "'AND'" + month2 + "'";
}
When DropDownList6 = March and DropDownList8 = June. Nothing appears in the gridview which im binding BUT if the swap them around so DDL6= June and DDL8 = March it works :S
Is there a work around so that i can have the months ordered in how the months are meant to be instead of being alphabetical
why are you really storing months as strings in the database?, if you follow that path, trust me you are even going to encounter much more serious problems down the road & they will be a hell to debug. You can always get the month part from any date or dateTime column value.
try this code, Hope this what you expected
SET #FromMonth = 'March'
SET #ToMonth = 'June'
SELECT
*
FROM
tbl_DR_data
WHERE
DATEPART(mm,CAST([Month]+ ' 1900' AS DATETIME)) >= DATEPART(mm,CAST(#FromMonth+ ' 1900' AS DATETIME))
AND DATEPART(mm,CAST([Month]+ ' 1900' AS DATETIME)) <= DATEPART(mm,CAST(#ToMonth+ ' 1900' AS DATETIME))
This is the MSDN Syntax for BETWEEN
test_expression [ NOT ] BETWEEN begin_expression AND end_expression
Why no results when When DropDownList6 = March and DropDownList8 = June?
With above values, your query becomes like
[Month] BETWEEN 'March' AND 'June'
Unfortunately, when you are filtering using BETWEEN, begin_expression should be less than or equal to end_expression. In your case, since you have stored months (names) as string in the database, March comes after June in alphabetical order and so above condition returns false and no results.
This is a fiddle example same as yours with no results.
You can get the month from a date/datetime field using various methods. In sql server, you can use;
//Month NUMBER
month(datefield) as month_Number
//Month NAME
datename(month,datefield) as month_Name
Just to give you worst side of your design. Just check the results of filtering by where month between 'april' and 'may'.
Your results include: August, December, February, January, July, June, March
Solution:
For the time since you don't have full date, I guess it would be better to update your database filed as below and change the datatype of [month] to int type;
update yourTable
set [month] = case [month] when 'January' then 1
when 'February' then 2
...
when 'December' then 12 end
Now change the data type of [month] to int type and then pass the month number from the code as
[month] BETWEEN 3 and 6
Also, try to avoid key words such as Month for field names.
I am not sure what your DB design is or even what the Month Fields data-type is, I agree with other first & foremost that this is not a good design as i cant think of a scenario where i can search only based on month. This should be a complete date fields.
It can give us better idea if you give us very brief about this functionality like where you want to use it & purpose.
Please don't take me as a critic... more details about your project can help us better understand & recommend solution. May be i am wrong as i may have not understand your question.
You can use nice solution given but think for the road ahead..
I have a linq-to-sql query that works by grouping the data it retrieve in days for a particular month:
var Output = from c ....
where .... // this is the month parameter
group c by c.TheTime.Date into daygroups
select new MyModel(){
Prop1 = (from x in daygroups
where....
select x.ID).Count()
}.ToList();
The problem is that this groups by datetime in terms of server time. I'd like to group them by interval of times so that if we're looking at the result with California time, we're really looking at a list of days that starts at midnight PST.
The query returns a count. The solution I've figured out for now would be to return all the raw data between the beginning and the end of the month in a certain timezone, and then rearranging the raw data in days with the correct timezone, and only then do the count.
Is there a better way to do this?
Try grouping by c.TheTime.Date.AddHours(-8).
However, I'm not sure whether that will work correctly.
I have a table with a datetime2 field and I need to get all rows out of it where the date is today. Rather oddly (in my opinion but I'm sure there's a valid reason for it) if I do:
MyTable.Where(t => t.Date == DateTime.Today).ToList()
it returns nothing even though there are entires with todays date.
What am I missing here? I thought that datetime2 allowed you to query like this instead of having to use greater than and less than to specify a timeframe?
Edit
I've tried using the .Date portion of the DateTime2 representation in Linq to SQL:
MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()
but I'm still getting nothing. Yet in my database there are rows with the value 2011-08-05 00:00:00.0000000 which is clearly today.
Edit again
I've ran the query:
List<string> dates = MyTable.Select(t => t.Date.Date.ToString()).ToList();
and I'm getting results like 2011-08-05, so that portion obviously works.
However, when I run
DateTime.Today.Date.ToString()
I get 08/05/2011 00:00:00. Could the addition of this time portion be causing the issue? How would I remove this?
Edit 3
Got it to work using the code:
MyTable.Where(t => t.Date.Date.ToString() == DateTime.Today.Date.ToString("yyyy-dd-MM")).ToList();
This seems hacky though (converting to a string before comparison) and surely there must be a cleaner way?
It sounds like the date in the database isn't actually today (8th May). It's probably 5th August.
It looks like your datetime2 field is called Date. You need to use the Date property of this Date field to ignore the time of day.
MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()
I have a table which holds clocking in/out records for every user :
RecID User In/Out ClockInOutTime
8 1 IN 25/02/2011 09:36:44
9 1 OUT 25/02/2011 11:36:44
10 1 IN 25/02/2011 12:36:44
11 1 OUT 25/02/2011 17:36:44
12 1 IN 26/02/2011 00:00:00
13 1 OUT 26/02/2011 12:00:00
14 1 IN 26/02/2011 09:00:44
15 1 OUT 26/02/2011 12:36:44
Any ideas how I can work out the total time worked for every month using LINQ?
cheers
SELECT (SELECT SUM(DATEDIFF(SECOND,[ClockInOutTime], GETDATE()))
FROM [swp].[dbo].[Table_1] t1
WHERE [In/Out] = 'IN'
AND t1.[User] = t.[User]) -
Coalesce((SELECT SUM(DATEDIFF(SECOND,[ClockInOutTime], GETDATE()))
FROM [swp].[dbo].[Table_1] t2
WHERE [In/Out] = 'OUT'
AND t2.[User] = t.[User]),0)
FROM [swp].[dbo].[Table_1] t
GROUP BY [User]
SQL way to solve this, not the best, but works even when last event don't have OUT timestamp i.e when last session still hasn't been closed.
This is non-trivial to do in either Linq or SQL. There is no easy way to link each OUT record with the corresponding IN record in SQL.
You have two options:
Querying the data and calculating in code within a for loop.
Changing the table schema like: RecID, User, ClockInTime, ClockOutTime
Option 1 is easy to implement, but I would seriously consider option 2. How do you define in your business rules that each IN record must be followed by a corresponding OUT record (or be last record)?
TimeSpan output = new TimeSpan(0,0,0);
using (var enumerator = input.GetEnumerator())
{
while (enumerator.MoveNext())
{
var begin = enumerator.Current.ClockInOutTime;
if(!enumerator.MoveNext())
break;
var end = enumerator.Current.ClockInOutTime;
output += (end - begin);
}
}
Yes, it isn't LINQ but I wanted to offer a solution - secondly, if the dates aren't alternating (so after an IN is always an OUT) it'll break.
There is no solution that will only use linq. This is due to the fact that you need to introduce error handling as well (if a user forgets to sign out, usually there is a maximum time that will be applied then etc).
I would group the data by user, order it by date time and then run through it in a for each and do the calculation within the for each.