Retrieve Records Less than 90 Days Old - sql

I'm trying to use the below code to bring back all records that are not older than 90 days from a table:
Set PlatinumList = db.OpenRecordset( _
"SELECT FORMATTED_CTN FROM CTN_LIST " _
& "WHERE ((Status='Available') AND (Category='Platinum')) " _
& "AND (In_Offer_List = True) " _
& "AND (DATEDIFF(day, Created_DT, current_date()< 90);", _
dbOpenSnapshot, dbReadOnly)
I keep getting a syntax error in query expression error when I try and run the code.
I think I'm formatting the date section of the code incorrectly.

The date token for day is "d" rather than day and your missing a closing )
.. AND (DATEDIFF("d", Created_DT, current_date()) < 90);"
(You also need current_date() as a vba func)

Related

Operator IN VBA excel

Could you help me please? I have tried to solve my problem for about 6 hours.
I have one table and there are 4 columns.
Columns:
Nio ,checked,date,time
I need to get data from the first and second columns, where I have to compare it by date and time.
I wanted to use the operator IN but excel gives me the error
Incorrect syntax near the keyword
Thanks for help.
strQueryQ7DrLeftElox =
"((Select nio,checked
FROM q7_dr_left_elox_incoming_inspection
where date >= '" & sDateFrom & "' AND date <= '" & sDateTo & "') IN (Select nio,checked from q7_dr_left_elox_incoming_inspection WHERE time = '19:55:06'))"
Both select statements query the same table, so simplify it by adding one more condition in the 1st query's WHERE clause:
SELECT nio,checked
FROM q7_dr_left_elox_incoming_inspection
WHERE date >= '" & sDateFrom & "' AND date <= '" & sDateTo & "'
AND time = '19:55:06'

Problem using where with date in SQL Statement

I am trying to execute an SQL statement in a VBA script. I have gotten the script to run, but it ignores the where with a date filter.
I have researched and tried every option I can find, but just cant seem to get it to work.
Set rs = conn.Execute("Select [adjustment_number], [status], [tax_adjusted],[amount], [gl_date],[creation_date],[apply_date],[comments],[type],[adjustment_type],[dbo].[Code_Combinations].[segment1], [dbo].[Code_Combinations].[segment10],[dbo].[Code_Combinations].[segment11],[dbo].[Code_Combinations].[segment12],[dbo].[Code_Combinations].[code_combination] FROM [dbo].[AR_ADJUSTMENTS_ALL] " & _
"left outer join [dbo].[Code_Combinations] on [dbo].[AR_ADJUSTMENTS_ALL].[CODE_COMBINATION_ID] = [dbo].[Code_Combinations].[CODE_COMBINATION_ID] where [gl_date] >= " & gldate & ";")
(Copying this from my comment above, into an answer, since this solved your problem)
SQL Server? Put single quotes around your date in the WHERE clause.
where [gl_date] >= '" & gldate & "';"
Assumes that gldate is a valid date, and [gl_date] is of a date datatype.

SQL/VBA - if/then/else for day of year when recordset has Leap Years and non Leap Years

Good Morning,
Here is my issue. I have a form where the user selects the date they want to work with. From there, in vba, I store the entered date in a variable (ytdDate) and then the day of year for that date is stored as a variable (dayOfYear). These variable values are then used in the following sql statement:
sqlYTDCounts = "SELECT Count(x.event_unique_id) AS total,
Year(occurrence_date) AS year " & _
"FROM (SELECT DISTINCT event_unique_id, occurrence_date
FROM events WHERE datepart('y',occurrence_date) <=" &
dayOfYear & _
") AS x GROUP BY Year(occurrence_date) HAVING
(((Year([occurrence_date]))>='" & _
DatePart("YYYY", ytdDate) - 10 & "') )"
So essentially what is happening is a recordset is retrieved where the day of the year for each [occurrence_date] is <= the day of the year from the date the user selected on the form.
The sql works great, but only for non Leap Years, for all Leap Years it is actually getting the day of the year before that from user selected date. As an example:
User selects July 23,2017
dayOfYear = 204
But for a Leap Year July 23rd is the 205th day of the year.
In my head, the solution seems simple enough: From the recordset check to see if the year of the occurrence is any of these years (2004,2008,2012,2016) and if the day of the year of the occurrence_date for that occurrence is >= 60 (the reason being is I can't just check if it is a leap year because LY and NonLY have the same day of year up until 60).
If both of these criteria are met, then the <=" & dayOfYear &_ part of the sql statement would be <=" & (dayOfYear + 1) & _
If non of the criteria are met then sql statement would remain as is.
Now, how to translate that into VBA is where I am stuck. I have tried using IF THEN ELSE statements with the sql statement but that hasn't worked (I am pretty sure I am not doing it correctly) =]
I really apologize if this is super convoluted and not making any sense, but any and all input/suggestions/assistance is GREATLY appreciated.
Thanks,
Mark
Try this method using DateAdd which always handles leap years correctly:
sqlYTDCounts = _
"SELECT Count(*) AS total, Year(occurrence_date) AS year " & _
"FROM " & _
" (SELECT DISTINCT event_unique_id, occurrence_date " & _
" FROM events " _
" WHERE DateDiff('d', DateAdd('yyyy', " & Year(ytdDate) & " - Year(occurrence_date), occurrence_date), occurrence_date) <= 0) AS x " & _
"GROUP BY Year(occurrence_date) " & _
"HAVING Year([occurrence_date]) >= " & Year(ytdDate) & " - 10)"
Edit2:
sqlYTDCounts = _
"SELECT Count(*) AS total, Year(occurrence_date) AS year " & _
"FROM " & _
" (SELECT DISTINCT event_unique_id, occurrence_date " & _
" FROM events " & _
" WHERE DateDiff('d', DateAdd('yyyy', " & Year(ytdDate) & " - Year(occurrence_date), occurrence_date), #" & Format(ytdDate, "yyyy\/mm\/dd") & "#) >= 0) AS x " & _
"GROUP BY Year(occurrence_date) " & _
"HAVING Year([occurrence_date]) >= " & Year(ytdDate) & " - 10"

comparison between dates not working in ms access

Using Access 2013
I have table in Access where Column "DueDate" is defined as "Date/Time"
System default date format is dd/mm/yyyy
Want to change List's Row Source through VBA, based on value in a textbox "txtDueDateUpto".
So, that I get all the task where the dude date is less than equal to the date entered by user in "txtDueDateUpto"
mySql = "SELECT TaskTbl.TaskID "
& " FROM TaskTbl " _
& " WHERE " _
& " DueDate is not Null and " _
& " Format (DueDate," & """dd/mm/yyyy""" & ") <= " & Format(CDate(Me.txtDueDateUpto.Value), "dd/mm/yyyy") _
Me.listTask.RowSource = mySql
I have 3 Tasks for testing purpose.
where DueDate is saved as
TaskID DueDate
1 25-17-2015
2 01-07-2015
3 29-06-2015
and, value in txtDueDateUpto is 06-07-2015
txtDueDateUpto format property is set to "Short Date"
I was expecting taskID 2,3 to be returned, with the given SQL, but I am getting taskID 2
I sat all night, trying many permutations and combinations, but cannot get what is that, I am doing wrong.
newbie for Access VBA. Pls help, thanks in advance.
Always handle dates as dates, not strings, no exceptions.
If your textbox has been assigned a date/time format, you don't even have to use CDate or DateValue because Access then reads that value as of data type Date.
However, you must concatenate the value with the SQL code as a properly formatted string expression of the date value:
mySql = "SELECT TaskTbl.TaskID "
& " FROM TaskTbl " _
& " WHERE " _
& " DueDate is not Null and " _
& " DueDate <= #" & Format(Me!txtDueDateUpto.Value, "yyyy\/mm\/dd") & "#"
If you are going to format the dates as strings -- and compare them -- then always use YYYY-MM-DD format:
& " Format (DueDate," & """yyyy-mm-dd""" & ") <= " & Format(CDate(Me.txtDueDateUpto.Value), "yyyy-mm-dd") _
However, I'm pretty sure that MS Access can just do date comparisons without the conversion:
DueDate <= CDate(Me.txtDueDateUpto.Value)

SQL ORDER BY on Update- update last record with condition

I am trying to update the last record of table Log (the field with the latest TimeAccessed) given that TimeExited is null, and the computername is the same as the "cm" parameter. I have this but get error, "missing semicolon at end of sql statement"
what is wrong??
dbs.Execute "UPDATE Log " _
& "SET TimeExited = " & Format(CloseTime, "\#hh:mm:ss AMPM\#") _
& " WHERE TimeExited is NULL AND ComputerName = '" & cm & "'" _
& " ORDER BY TimeAccessed DESC" _
& " LIMIT 1; "
nothing wrong with first 2 lines, work perfectly fine, it's the last two that give problems
Access SQL doesn't use LIMIT n it uses TOP n, and as mentioned in the other question cited in the comments to your question, you aren't allowed to use TOP in the way you've described. Instead, you'll need to do something along these lines:
UPDATE Log
SET TimeExited = CloseTime
WHERE TimeExited IS NULL
AND ComputerName='r2d2'
AND TimeAccessed IN
(
SELECT TOP 1 TimeAccessed
FROM Log
WHERE TimeExited IS NULL
AND ComputerName='r2d2'
ORDER BY TimeAccessed DESC
)