Is there anyway I can include the Max or Top1 function into the below.
I'm trying to return the latest date value however due to the database returning date & time format I need to use the FORMAT syntax to correct this.
I've tried in both the SELECT and WHERE clauses but can't get it to work
sSql = "SELECT FORMAT(Total.StockDate, 'dd/mm/yy' ) AS DateRev FROM " & Mailbox & Totals & " WHERE(Total.UnitCode=" & Sheets("Pipe Cleaning").Range("C4") & " )"
Well you can do it as a subquery:
sSql = "SELECT FORMAT(StockDate, 'dd/mm/yy' ) AS DateRev FROM " & _
" (SELECT MAX(StockDate) StockDate FROM " & Mailbox & Totals & _
" WHERE(Total.UnitCode=" & Sheets("Pipe Cleaning").Range("C4") & " ) )"
But it may be cleaner to just get the date value and then format in VBA:
sSql = " (SELECT MAX(StockDate) StockDate FROM " & Mailbox & Totals & _
" WHERE(Total.UnitCode=" & Sheets("Pipe Cleaning").Range("C4") & " ) "
.. execute SQL, store result in dtDate
sDate = Format(dtDate, "dd/mm/yy")
Just wrap the format in a MAX statement. You have to specify the months as caps MM though.
Sample:
Select Max(Format(mydatefield, 'dd/MM/yy')) from mytable
Related
In my Project I have Orders which contain an amount of Hours which have to be invoiced by a Rate, both of them are stored in tables. The Orders have a ValidFrom date. All Orders have to be invoiced by the last Rate where the ValidFrom is before the Order.TimeStamp.
The solution that I've tried is:
OrderDate = DLookup("TimeStamp", "Order", "OrderID=" & ThisOrderID & ")
LastRateDate = DMAX ("ValidFrom", "CompanyRate", "CompanyID=" & ThisCompanyID & " AND ValidFrom <=" & OrderDate)
CompanyRate = DLookup ("Rate","CompanyRate", "CompanyID=" & ThisCompanyID & " AND "ValidFrom =" & LastRateDate)
This gives several different errors:
without semicolons (as written): Syntax error missing Operator.
with single semicolon ' Datatype Conflict
with double semicolon " (chr(34)) Datatype Conflict
I use a german Computer, with german as Windows and MS-Access language. I run the MS-Access 2013
How should I solve this?
Try this using the proper syntax:
OrderDate = DLookup("TimeStamp", "Order", "OrderID = " & ThisOrderID & "")
LastRateDate = DMax("ValidFrom", "CompanyRate", "CompanyID = " & ThisCompanyID & " AND ValidFrom <= #" & Format(OrderDate, "yyyy\/mm\/dd") & "#")
CompanyRate = DLookup("Rate", "CompanyRate", "CompanyID = " & ThisCompanyID & " AND ValidFrom = #" & Format(LastRateDate, "yyyy\/mm\/dd") & "#")
I have constructed a query to select all dates between a date range which is inputted by the user.
When the user selects the date before todays date, the current date or a day after the current date it brings back dates not within the date range.
Please see my examples below:
Before todays date returning incorrect dates in range:
Selecting date 3 days after current date query query perfectly:
Option Compare Database
Private Sub Command121_Click()
Dim strCriteria, task As String
strCriteria = "([PromisedDeliveryDate] >= #" & Me.DateFrom & "# And [PromisedDeliveryDate] <= #" & Me.DateTo & "#)"
task = "select * from SageOrderLine_Live where (" & strCriteria & ")"
DoCmd.ApplyFilter task
End Sub
EDIT: How would I add to query by the customeraccountnumber as well? I have tried to add it on but it's bringing up an error:
DoCmd.ApplyFilter _
"select * from SageOrderLine_Live where " & _
"[PromisedDeliveryDate] >= " & Format(Me.DateFrom, "\#mm\/dd\/yyyy\#") & " and " & _
"[PromisedDeliveryDate] <= " & Format(Me.DateTo, "\#mm\/dd\/yyyy\#") & " and " & _
"[CustomerAccountNumber] = " & Me.CustomerAccount & ""
The "Enter parameter box" is appearing when selecting search:
When referencing date values within a SQL statement, you will need to ensure that such dates adhere to the expected format of:
#mm/dd/yyyy#
Else, a date such as 08/11/2019 (8th November 2019) will be interpreted within the SQL as 11/08/2019 (11th August 2019), yielding the results that you are witnessing.
You can achieve this using the Format function:
Format(Me.DateFrom, "\#mm\/dd\/yyyy\#")
Here, the additional backslashes \ preceding the octothorpes & forward slashes act as Escape Characters, forcing MS Access to display the next character as a literal.
For example:
?Format(Date(), "\#mm\/dd\/yyyy\#")
#11/09/2019#
In your code, this might be written:
Private Sub Command121_Click()
DoCmd.ApplyFilter _
"select * from SageOrderLine_Live where " & _
"[PromisedDeliveryDate] >= " & Format(Me.DateFrom, "\#mm\/dd\/yyyy\#") & " and " & _
"[PromisedDeliveryDate] <= " & Format(Me.DateTo, "\#mm\/dd\/yyyy\#")
End Sub
Alternatively, you could reference the form controls directly within the SQL statement, in which case, no formatting is required:
Private Sub Command121_Click()
DoCmd.ApplyFilter _
"select * from SageOrderLine_Live where " & _
"[PromisedDeliveryDate] >= [Forms]![YourFormName]!DateFrom and " & _
"[PromisedDeliveryDate] <= [Forms]![YourFormName]!DateTo "
End Sub
(Updating YourFormName to the name of your form, of course).
EDIT: If you wish to add the CustomerAccountNumber to the filter, since this is a text field, you'll need to enclose the value with either single or double quotes, e.g. using single quotes:
DoCmd.ApplyFilter _
"select * from SageOrderLine_Live where " & _
"[PromisedDeliveryDate] >= " & Format(Me.DateFrom, "\#mm\/dd\/yyyy\#") & " and " & _
"[PromisedDeliveryDate] <= " & Format(Me.DateTo, "\#mm\/dd\/yyyy\#") & " and " & _
"[CustomerAccountNumber] = '" & Me.CustomerAccount & "'"
Or double-quotes:
DoCmd.ApplyFilter _
"select * from SageOrderLine_Live where " & _
"[PromisedDeliveryDate] >= " & Format(Me.DateFrom, "\#mm\/dd\/yyyy\#") & " and " & _
"[PromisedDeliveryDate] <= " & Format(Me.DateTo, "\#mm\/dd\/yyyy\#") & " and " & _
"[CustomerAccountNumber] = """ & Me.CustomerAccount & """"
Can any body help me with the following SQL statement?
What am I doing wrong here?
It is giving me no result however there should be some...
The desired result should be a list or errorsdetails with the total number of times it is in the database (mdb) based on the selected date-period.
PS sorry for my badly written English..
Many thanks
Koen
sSQL = "SELECT ErrorDetail, count(*) AS totalcount FROM tblErrors WHERE DisplayName = " & cbox_modules.Text & " AND ErrorDate BETWEEN #" & startdate & "# AND #" & enddate & "# GROUP BY ErrorDetail"
Assuming the "DisplayName" column is a string, ensure you surround it with apostrophes:
SELECT
ErrorDetail,
COUNT(*) AS totalcount
FROM tblErrors
WHERE DisplayName = '" & cbox_modules.Text & "' AND ErrorDate BETWEEN #" & startdate & "# AND #" & enddate & "#
GROUP BY ErrorDetail
I have a macro that opens a MS Project file and copies the content itself in an Access table. I make it through Excel because afterwards I need to make some queries and copy the results into some cells.
This code below creates or drops the table:
Dim dbX As DAO.Database
If Err.Number = 0 Then
dbX.Execute ("DROP TABLE " & dbName & ";")
End If
dbX.Execute ("CREATE TABLE " & dbName & " ([ID] INTEGER, [TaskID] INTEGER, [Milestone] TEXT(3), [TaskName] TEXT(255), " & _
"[pComplete] TEXT(10), [Start] DATE, [Finish] DATE, [BaselineStart] DATE, [BaselineFinish] DATE, " & _
"[ActualStart] DATE, [ActualFinish] DATE);")
Err.Clear
This fills the table using the project fields:
dBquery = "INSERT INTO " & tName & "(ID, TaskID, Milestone, TaskName, pComplete, Start, Finish, BaselineStart, BaselineFinish, " & _
"ActualStart, ActualFinish)" & _
" VALUES (" & t.ID & ", " & t.UniqueID & ", '" & t.GetField(pjTaskMilestone) & "', '" & t.Name & "', '" & t.GetField(pjTaskPercentComplete) & _
"', " & RetrieveDate(t.Start) & ", " & RetrieveDate(t.Finish) & ", " & RetrieveDate(t.BaselineStart) & ", " & _
RetrieveDate(t.BaselineFinish) & ", " & RetrieveDate(t.ActualStart) & ", " & RetrieveDate(t.ActualFinish) & ");"
dB.Execute dBquery
RefreshDatabaseWindow
This is the function used to retrieve the date fields:
Function RetrieveDate(D As Variant) As Variant
If D = "NA" Then
RetrieveDate = "NULL"
Else
RetrieveDate = "#" & D & "#"
End If
End Function
The problem that I have is that when the code finds an ambiguous date, uses the American format, so when I try to run queries, the results are not correct.
For example, here I have a task with its dates and everything:
Whatever the date format I use it spins the date or it just doesn't insert the dates into the DB.
For example, in this table, the dates are inserted in decimal format. The same task in the database is:
In this image above we can see fewer fields because I've just taken the ones that I need.
So, if for example I make a query to retrieve the date in 'dd/mm/yyyy' format this same task, I get:
SELECT FORMAT(Start, "dd/mm/yyyy"), FORMAT(Finish, "dd/mm/yyyy")
FROM ow18_072014
WHERE TaskID = 202;
I have tried to convert the format to yyyy/mm/dd but the dates are not pasted into the table.
Another conversion I have tried is to change date format from Project but now Access changes some dates without any sense: a date equal to 20 Jun 2014 in MS Project becomes 15/11/2013 in MS Access.
You do not give us much information, and in the future, if you want people to actually have a chance of helping you, you have to put more effort in your question: give us some code you tried, some data example, etc.
Anyway, the issue is that by default, Access interprets literal dates as #mm/dd/yyyy#, except when it's unambiguous, like #25/12/2014#.
There are 2 ways to solve this issue: if you pass a litteral date to Access, use the #yyyy/mm/dd# ISO format instead because it's unambiguous and it will work in every locale.
Alternatively, convert your date to a decimal value and pass that to your Access date field instead, like CDec(myDate), will pass something like 41851.3465625 to Access and it will work.
The GetField method of the Task object returns a string value. For date fields, it returns the value in the format selected by the user (or set by the DefaultDateFormat property of the application object).
The simplest solution is to use the explicit properties of the Task object instead of the GetField method.
Modify your SQL statement to something like this:
dBquery = "INSERT INTO " & t.Name & "(ID, TaskID, Milestone, TaskName, pComplete, Start, Finish, BaselineStart, BaselineFinish, " & _
"ActualStart, ActualFinish)" & _
" VALUES (" & t.ID & ", " & t.UniqueID & ", '" & t.Milestone & "', '" & t.Name & "', '" & t.PercentComplete & _
"', " & RetrieveDate(t.Start) & ", " & RetrieveDate(t.Finish) & ", " & RetrieveDate(t.BaselineStart) & ", " & _
RetrieveDate(t.BaselineFinish) & ", " & RetrieveDate(t.ActualStart) & ", " & RetrieveDate(t.ActualFinish) & ");"
I have a current sql query I am using in vb.net to get some data returned to a datagridview. I am checking against the year, month and date of the date time picker to get the necessary information returned from the selected table. My query works fine minus the case statement part to check for specific dates. Can anyone help me fix this query or suggest an alternative method?
"SELECT * FROM " & Me.SelectedTable.SelectedItem.ToString & "
WHERE(Datepart(yyyy," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Year & "' AND '" & Me.DateTimePicker2.Value.Year & "'
AND Datepart(mm," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Month & "' AND '" & Me.DateTimePicker2.Value.Month & "'
AND Datepart(dd," & colName & ") <= " & Me.DateTimePicker1.Value.Day
& " CASE WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & "
THEN Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month
& " Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31 END)"
First, your query is open to SQL injection attacks. You need to fix it by parameterizing your query.
Next, you do not need the CASE there: you can express your logic as a composite logical condition.
I changed the query from one that uses a dynamic column name defined by the value of the colName variable to use col for better readability. I also defined parameters for the values that come from various pickers. You will need to set them on your prepared command before querying.
The part of most interest is at the bottom: I rewrote your CASE as a three-part logical condition that evaluates one of three parts based on the settings of #month1 and #month2, which represent the month values from DateTimePicker1 and DateTimePicker2.
SELECT * FROM Table
WHERE (Datepart(yyyy, col) BETWEEN #year1 AND #year2
AND Datepart(mm, col) BETWEEN #month1 AND #month2
AND Datepart(dd, col) <= #day1
AND (
(Datepart(mm, col)=#month1 AND Datepart(dd, col) = #day1)
OR (Datepart(mm, col)=#month2 AND Datepart(dd, col) = #day2)
OR (Datepart(dd, col) BETWEEN 1 AND 31)
)
It looks like you have just forgotten then "THEN" at the end of your second condition.
So, make it:
CASE
WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & " THEN
Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month & " **THEN**
Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31
END