AddDays is LINQ to SQL - sql

I am trying to user the AddDays function in LINQ to SQL inside the Where clause.
I need to return all the results that are greater than the current date plus a user defined range.
Here is my code.
Where (DateTime.Now >= DateTime.Now.AddDays(UserEnteredDaysToAdd)
What am I doing wrong? or is it even possible?
Thank you,
Edit:
Sorry I made a mistake. I want to get all the records that are in between the current date and an number of days the user enters or is stored in the db.
So it should read, Where (StockOrderDate >= DateTime.Now.AddDays(UserEnteredDaysToAdd))

Lets have a look at your query:
Where (DateTime.Now >= DateTime.Now.AddDays(UserEnteredDaysToAdd))
Apart from not having the right body, you're checking if today is greater or equal to today plus x days. That won't ever be true if you do not allow negative values for UserEnteredDaysToAdd.
Your data structure (result) must have some date property you want to check for, like ResultDate, then your query would look like
IEnumerable<ResultType> results;
...
var resultsAfterDate = results.Where(r => r.ResultDate >= DateTime.Now.AddDays(UserEnteredDaysToAdd));

Related

Using VBscript and SQL on an Access database how do you select records based on a date comparison with todays date

This sounds like a very naive question but I can not get this simple requirement to work. A selection is made on one page of the website which passes a parameter time_period (which is 1, 7, 31 or 365) to the next page which should list all of the selected records where the LastUpdated date (a standard date field in Access db) is within that many days of the current date.
With single digit numbers (1 and 7) I get a result, but not 100% accurate and with 31 and 365 only very strange results. I guess there is an inconsistency in formats somewhere but I am at a loss to find a solution.
Dim my_time_period
my_time_period = Request.QueryString("time_period")
selection_list.Source = "SELECT * FROM document WHERE DateDiff('d',LastUpdated,now) <= '"+my_time_period+"'"
I have tried hard coding a number as below but get the same results.
selection_list.Source = "SELECT * FROM document WHERE DateDiff('d',LastUpdated, now) <= '7'"
I have also tried using Today instead of now but it gets thrown out as an error. Can anyone please help? Thank you
You're comparing a number
DateDiff('d',LastUpdated, now)
to a string
'7'
Instead compare a number to a number:
"SELECT * FROM document WHERE DateDiff('d',LastUpdated,now) <= "+my_time_period
Note the difference: no single quotes
Also be aware this is inviting SQL Injection.
Also be aware that in a database that uses indexes, this expression should be rewritten something like this:
SELECT * FROM document WHERE LastUpdated > DateAdd('d',now,-"+my_time_period+")"
That way you're comparing a column (which may be indexed) to a fixed value. It doesn't matter so much in MS Access though

How to count a feature x if y condition is true (bigquery)

I am new in machine learning and I am running one of my first machine learning problems. I do a lot of research by myself but could not find the solution for this question.
I am creating new variables from my dataset in Bigquery. One of the variables consists in count a variable (x) if a condition in variable (y) is met. I cannot use WHERE or HAVING since the condition is only related to the calculation of this specific variable.
The code is more or less like this:
COUNT(DISTINCT sessionid IF(date > “2018-06-01” && date < “2018-06-30”))
AS sessions_lastmonth
I know that this code is not correct and could not be but is just a way to express more or less what I need.
The goal is to know the number of sessions in a certain period. I cannot use the count for date because in one day you can have more than one session and not every row is a different session (a session can have several lines because the user can go through many pages in the same session).
Thank you!
Below for BigQuery Standard SQL
COUNT(DISTINCT IF(date >= '2018-06-01' AND date <= '2018-06-30', sessionid, NULL)) AS sessions_lastmonth
You said you couldn't use WHERE so I am going to assume that the answer that proposes you use WHERE won't fly?
I think you might need to use CASE instead, so your query might look something like:
COUNT(DISTINCT CASE WHEN date > “2018-06-01” AND date < “2018-06-30” THEN sessionid ELSE NULL END) AS sessions_lastmonth
That syntax might not be right, but it might help you onto the right track?

sqlalchemy select by date column only x newset days

suppose I have a table MyTable with a column some_date (date type of course) and I want to select the newest 3 months data (or x days).
What is the best way to achieve this?
Please notice that the date should not be measured from today but rather from the date range in the table (which might be older then today)
I need to find the maximum date and compare it to each row - if the difference is less than x days, return it.
All of this should be done with sqlalchemy and without loading the entire table.
What is the best way of doing it? must I have a subquery to find the maximum date? How do I select last X days?
Any help is appreciated.
EDIT:
The following query works in Oracle but seems inefficient (is max calculated for each row?) and I don't think that it'll work for all dialects:
select * from my_table where (select max(some_date) from my_table) - some_date < 10
You can do this in a single query and without resorting to creating datediff.
Here is an example I used for getting everything in the past day:
one_day = timedelta(hours=24)
one_day_ago = datetime.now() - one_day
Message.query.filter(Message.created > one_day_ago).all()
You can adapt the timedelta to whatever time range you are interested in.
UPDATE
Upon re-reading your question it looks like I failed to take into account the fact that you want to compare two dates which are in the database rather than today's day. I'm pretty sure that this sort of behavior is going to be database specific. In Postgres, you can use straightforward arithmetic.
Operations with DATEs
1. The difference between two DATES is always an INTEGER, representing the number of DAYS difference
DATE '1999-12-30' - DATE '1999-12-11' = INTEGER 19
You may add or subtract an INTEGER to a DATE to produce another DATE
DATE '1999-12-11' + INTEGER 19 = DATE '1999-12-30'
You're probably using timestamps if you are storing dates in postgres. Doing math with timestamps produces an interval object. Sqlalachemy works with timedeltas as a representation of intervals. So you could do something like:
one_day = timedelta(hours=24)
Model.query.join(ModelB, Model.created - ModelB.created < interval)
I haven't tested this exactly, but I've done things like this and they have worked.
I ended up doing two selects - one to get the max date and another to get the data
using the datediff recipe from this thread I added a datediff function and using the query q = session.query(MyTable).filter(datediff(max_date, some_date) < 10)
I still don't think this is the best way, but untill someone proves me wrong, it will have to do...

displaying records with a date at least one day greater then or = to today

I have a field in a table called DATEF. It displays dates as follows: 2013-11-25 08:30:00.000. The field is used to show appointment dates. What I need to show are future appointment dates from today or = to today. (Getdate) for some reason this is not working for me today. Appreciate the help. Thank you.
Try this... you're probably failing to factor in the time component. (This is for SQL Server, you'll have to find the equivalent for your respective environment)
SELECT <SOMETHING>
FROM TABLE
WHERE DATEF >= CONVERT(DATE,GETDATE())

Access SQL Subtract Dates excluding weekends

I am able to run the query and update the days from the date it was created. However I would like to exclude weekend days, just Monday thru Friday.
Example:
UPDATE [Table1] SET [Table1].Days = DATE() - [Table1].DateCreated WHERE [Table1].Password = True AND [Table1].Complete = FALSE;
This will update the days to the value from the created date to current date, which would be 1,2,3, etc. However I need this to exclude the weekends. I don't run queries very often but I would like create this query.
Please help, thank you.
It you will be running your query from within an Access session, you can use a VBA user-defined function to compute the number of weekdays between two dates.
For example, consider the WorkingDays() function from the Access Web: Calculate Number of Working Days. If I understand your query correctly, I think this may do what you want:
UPDATE [Table1]
SET [Table1].Days = WorkingDays([Table1].DateCreated, DATE())
WHERE [Table1].Password = True AND [Table1].Complete = FALSE;
On that same page, you can find a WorkingDays2() function which would allow you exclude holidays from the workdays count if that's useful. You would need to set up a table for your holidays though.
If you will be doing this from outside an Access session, like from classic ASP or Dot.Net, you won't be able to use a user-defined function in the query.