I have a query as below :
select column_date, field1, field2, sum(field3) from table1
where field1 like '*xyz' and
column_date between [please enter start date] and [please enter end date]
group by column_date, field1, field2
When I leave blank both the parameter boxes, the output is blank. But I want them in output as below
I want to display all records when I leave blank both parameter box
if I put date in any one of the parameter boxes, it should display only records for that date
If i put dates in both the parameter boxes, it should display all records between those dates.
This is my asp code to display the output. It works when I insert values in both the text boxes but if I left blanks any of them or both, it shows error.
<html>
<body>
<%
dim startdate, enddate
startdate = Request.Form ("startdate")
enddate = Request.Form("enddate")
set conn = Server.CreateObject ("ADODB.Connection")
conn.open "connectionname"
set rs = Server.CreateObject ("ADODB.Recordset")
Sqlquery = "queryname '" & startdate & "', '" & enddate &'" "
rs.open sql, conn %>
<table>
<tr>
<%
For each x in rs.fields
response.write ("<th>" & x.name & "</th>")
next %> </tr>
<tr><% Do Until rs.EOF %>
<% For each x in rs.Fields %>
<td>Response.write (x.value)</td>
<%next
rs.movenext %>
</tr>
<% loop
rs.close
conn.close %>
</table>
</body>
</html>
I would start with a plain SELECT query to figure out the WHERE clause. Once you get that working correctly, convert it to a GROUP BY query.
So see if this one targets the correct records:
PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT t.field1, t.field2, t.field3, t.column_date
FROM table1 AS t
WHERE
t.field1 Like '*xyz'
AND (
(t.column_date Between [Start Date] And [End Date])
OR ([Start Date] Is Null And t.column_date = [End Date])
OR (t.column_date = [Start Date] And [End Date] Is Null)
OR ([Start Date] Is Null And [End Date] Is Null)
);
Assuming that first query returns the correct rows, I think this GROUP BY query may give you what you want.
PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT t.column_date, t.field1, t.field2, sum(t.field3)
FROM table1 AS t
WHERE
t.field1 Like '*xyz'
AND (
(t.column_date Between [Start Date] And [End Date])
OR ([Start Date] Is Null And t.column_date = [End Date])
OR (t.column_date = [Start Date] And [End Date] Is Null)
OR ([Start Date] Is Null And [End Date] Is Null)
)
GROUP BY t.column_date, t.field1, t.field2;
If running this query from classic ASP, you will need to substitute the ANSI wild card character % for the Access-style * wild card.
t.field1 Like '%xyz'
Or consider using ALike and the ANSI wild card instead of Like. That way the query will always operate the same without needing to switch wild cards.
t.field1 ALike '%xyz'
Also, with classic ASP, run the query from an ADO Command object, and supply values for the parameters.
Related
Instead of using Nested If statements, I was wondering if there is a way to void out parts of a string query if cell value is left blank.
Cell structure is as below:
Cell values from these parameters will get passed into vba code that queries a database.
Ideally I don't want to create an individual query for each selection type - and I have it dynamically querying from location already. I want to extend the query to include possible combinations of start, end, value >, value <, while also making it so that if cell value is left blank, then ignore that parameter. So say
SELECT *
from database
WHERE location = 'cell_loc'
AND Value >= 'cell_value'
AND Value <= 'cell_value'
AND Start >= 'cell_date'
AND End <= 'cell_date'
Now imagine that Start is left blank, meaning I want to query from first data point in the database:
I could write a nested if to handle this, but was wondering if there was a way to void out a query parameter so that I could just have a single query fed to database with different parameters changing based off cell data?
Something along the lines of:
SELECT *
from database
WHERE location = 'cell_loc'
AND Value >= 'cell_value'
AND Value <= 'cell_value'
AND Start >= 'cell_date' --> this would be voided out
AND End <= 'cell_date'
Using the coalesce() function you can put an equality condition in your WHERE clause. This is a common SQL trick to deal with null parameters or null values in the data.
SELECT *
from database
WHERE location = 'cell_loc'
AND Value >= 'cell_value'
AND Value <= 'cell_value'
AND (Start >= 'cell_date' OR Start = coalesce('cell date', Start))
AND End <= 'cell_date'
Here's a very basic example:
Sub Tester()
Dim sWhere As String, sql As String
sql = "Select * from myTable "
sWhere = ""
BuildWhere sWhere, "id = <v>", Range("A5")
BuildWhere sWhere, "pName = '<v>'", Range("B5")
BuildWhere sWhere, "pDate > '<v>'", Range("C5")
If Len(sWhere) > 0 Then
sql = sql & " where " & sWhere
Debug.Print sql
'run query
Else
'don't run if no criteria ?
End If
End Sub
'add a where clause only if `c` has a value
Sub BuildWhere(ByRef sWhere As String, test As String, c As Range)
Dim v
v = Trim(c.Value)
If Len(v) > 0 Then
If Len(sWhere) > 0 Then sWhere = sWhere & vbLf & " and "
sWhere = sWhere & Replace(test, "<v>", v)
End If
End Sub
Hello everyone I am at a dilemma I am trying to find possible multiple accounts made by the same person by comparing the records, my main problem is how do you compare the current row value to the next value? By this I mean like this MI(i)=MI(i+1) "MI" is the field that I am targeting and i represents the current row, so what this is suppose to do is compare the current value to the next value. But it does not seem to work in vba is it done a diffferent way? To filter should I use rs.Filter or should I use Me.Filter because I want the filtered table to show up in my splitform.
Current Example Table that I am working with:
Number MI First Name Last Name DOB
15241543 123456789 James Matheson 2/25/1980
15241543 123456789 Jams Matheson 2/25/1980
12345679 124512451 Monroe Matheson 3/25/1980
12345679 124512451 Monro Matheson 3/25/1980
54789654 152415241 Dilan Pumley 4/23/1970
54789658 154215246 Michael Lan 1/30/1989
Final table that should appear is this:
Number MI First Name Last Name DOB
15241543 123456789 James Matheson 2/25/1980
15241543 123456789 Jams Matheson 2/25/1980
12345679 124512451 Monroe Matheson 3/25/1980
12345679 124512451 Monro Matheson 3/25/1980
Private Sub buttonSort_Click()
Dim i As Integer
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("deleteYo")
For i = 0 To rs.RecordCount - 1
'Comapred the current DOB cell value to the next DOB cell value and some other conditions are set such as Current First Name does not equal the next First Name value
If DOB(i) = DOB(i + 1) And [First Name](i) <> [First Name](i + 1) Or [Last Name](i) <> [Last Name](i + 1) And Number(i) = Number(i + 1) Or MI(i) = MI(i + 1) Then
'Filters the current value if the conditon is passed
Me.Filter = "[First Name]" & [First Name](i).Value & "'"
'Filter the next value also to append the filtered values so that they will not be overwritten.
Me.Filter = Me.Filter & "[First Name]" & [First Name](i + 1).Value & "'"
Else
End If
rs.MoveNext
Next i
Me.FilterOn = True
rs.Close
Set rs = Nothing
db.Close
End Sub
Please Note I have tried using a query with SQl statement for this which does not work properly perhaps because this data is practically millions of records and also because the UI is in the form and when the filtered values are applied I would like them to show up at the table at the bottom of the split form.
You can try using a corelated subquery.
SELECT t.ID, t.[First Name], t.[LastName], t.MI
FROM YourTable AS t
LEFT JOIN
(SELECT t2.id, t2.[First Name], t2.[Last Name], t2.MI
FROM YourTable AS t2) AS temp
ON t.MI = temp.MI
WHERE t.[First Name] != t2.[First Name]
OR
t.[Last Name] != t2.[Last Name];
This is going to compare each field with the same MI value and retrieve records where the first and last names are not similar.
You can adjust the fields to better fit your table schema.
I got error in populating the result of my query to access form but it gives me "The recordsource [query here] specified on this form or report does not exist
Here is my code:
Me.RecordSource = "SELECT Division, Station, EmployeeNumber, BranchCode, AccountNumber, LedgerSetNumber, EmployeeName, EffectDate, TermDate, Amount, BillingType, DateBilled, PolicyNumber, BillingStatus, UpdateStatus, DateUpdated, SequenceNumber FROM DepEdTempBilling WHERE (UpdateStatus<>'Billed') ORDER BY Division, Station, EmployeeNumber, BranchCode, AccountNumber, LedgerSetNumber, EmployeeName"
screenshot:
Your logic is correct. For some reason that doesn't work. I did the same thing with my code. Here it is, hopefully this helps.
Me.RecordSource = "SELECT tblQuoteMaster.[Quote Number], tblQuoteMaster.Status, tblQuoteMaster.Prefix, tblQuoteMaster.[Rev Number], tblQuoteMaster.[AWC Rep], tblQuoteMaster.Estimator, tblQuoteMaster.Customer, CUSLST.Name1 AS Company, tblQuoteMaster.CustomerID, tblQuoteMaster.[Approx Value], tblQuoteMaster.Currency, tblQuoteMaster.Decription, tblQuoteMaster.[Date Received], tblQuoteMaster.[Date Sent], tblQuoteMaster.[Follow Up Date], tblQuoteMaster.[Contact for Quote], tblQuoteMaster.ProductCode FROM (tblQuoteMaster INNER JOIN CUSLST ON tblQuoteMaster.CustomerID = CUSLST.[Account Code]) INNER JOIN tblContact ON CUSLST.[Account Code] = tblContact.[Customer Number] WHERE (" & strSQL & ");"
I have seen some people assign their recordset to the RecordSource. That would always give me your error. For example:
Dim rcd As RecordSet
Set rcd = db.OpenRecordset("SELECT.....")
Me.RecordSource = rcd.Name
Have re-made you table and form and tested, This error occurs when the Property Sheet (Access window not VBA editor) Form/Record Source: has “[query here]” in it clear this line out and try again, if that does not work try a clean new form with this statement. The command itself and SQL appear to be ok.
My query keeps returning the last date for ONRENT and CLOSED for the same piece of equipment when I add the column "AVAILABILITY". I only want the last entry for each piece of equipment.
Here is my query:
select max([No_]), [Start Date], [Availability Status]
from [Rental Line]
group by [No_], [Start Date], [Availability Status]
If I'm understanding your question correctly, you want only the last availability status for each piece of equipment defined by No_, where "last" would be defined by the latest start date. If so, this should work:
Try this:
select RL.[No_], RL.[Start Date], RL.[Availability Status]
from [Rental Line] RL
join
(
select
No_,
MAX([Start Date]) AS [LastStartDate]
from [Rental Line] RL1
group by No_
) X on RL.No_ = X.No_ AND RL.[Start Date] = X.[LastStartDate]
select max([No_]), [Start Date], [Availability Status]
from [Rental Line]
group by [No_], [Start Date], [Availability Status]
order by [AVAILABILITY] DESC
I have a user inputed date format of mm/dd/yyyy. I want to use this input in a query to act as a filter (start and end time). The actual date stored in the datebase was set with now(), so it has the format mm/dd/yyyy XX:XX:XX AM/PM.
How can I use these inputed dates in my filter? (When I tried out an mm/dd/yyyy input I was returned a Report with no values, but if I added the time, it worked, but I don't want the user to have to enter the time.)
Right now I am using simple input boxes for the input. I really would like to create a calendar popup (and I see tutorials online). Would the solution change if I changed over to a Calendar?
EDIT:
Here is my code, to make it eaiser to understand the issue.
Dim startDate As Date
Dim endDate As Date
startDateString = InputBox("Enter a start date.")
endDateString = InputBox("Please enter and end date.")
Reports![rpt_Inventory_Update].RecordSource = "MyQuery"
Reports![rpt_Inventory_Update].Filter = "Modification_Date BETWEEN #" & startDate & "# AND #" & endDate & "#"
Reports![rpt_Inventory_Update].FilterOn = True
When you compare to the field with Now(), you could change it to be compared to DateValue(Now())
Now() = Date() returns False
DateValue(Now()) = Date() returns True
I figured it out. This is my new code:
startTime = TimeValue("00:00:00")
endTime = TimeValue("23:59:59")
startDate = startDate + startTime
endDate = endDate + endTime
Reports![rpt_Inventory_Update].RecordSource = "MyQuery"
Reports![rpt_Inventory_Update].Filter = "Modification_Date BETWEEN #" & startDate & "# AND #" & endDate & "#"
Reports![rpt_Inventory_Update].FilterOn = True
This makes sure that the start and end dates in the query have a full time stamp, and thus the query works!