SSRS lookup with datediff Incorrect result error showing in fields - sql

I have to write again this problem. I am not an expert in SSRS.
I have been trying to resolve this issue. Even though the fields are all the same datatype am still getting error and incorrect time difference in the filed in some fields.
I do not know what am doing wrong. This is the code. Please find below screen shot also.
enter code =Datediff(DateInterval.Minute, Fields!health_start_date.Value, Lookup(Fields!flight_date.Value & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value) , Fields!FL_DATE.Value & Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value), Fields!ATD.Value, "DataSetAIMS") ) MOD 60 & " mins "
here
The scenario is that the two fields Health start date and ATD have two different dataset which shows time of flight differently but the time difference is always in minutes. What am trying to do is to compare the two table with their hour and date using lookup to find difference in minutes

Okay, I think I see the problem: you're really close and this stuff trips us all up on occasion. In the LOOKUP function, I think you are joining the two data sets based on:
flight_date = FL_DATE, and
register_number = REG, and
HOUR(health_start_date) = HOUR(ATD)
Which is fine, but the ampersand (&) just "concatenates" strings together, and (a) your strings don't actually match, and (b) HOUR is a number, not a string.
(a) The "date" in the first data set is DDMMYYYY, and in the 2nd it is DDMMYY. I.e., "05222018" is not the same as "052818", so your lookup will not work. It's possible that they are stored correctly as date fields in the database and so the comparison will work fine, but better to force them to match. For that I'd recommend formatting each of the date strings into a standard format, like "FormatDateTime(Fields!flight_date.Value, DateFormat.VBShortDate)".
(b) Should be easy, just add ".ToString" after the parentheses, like "DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString()".
(c) I'm assuming the register_number and REG are formatted the same.
Given all that, your new LOOKUP function might look something like this:
=Datediff(DateInterval.Minute,
Fields!health_start_date.Value,
Lookup(
FormatDateTime(Fields!flight_date.Value, DateFormat.VBShortDate) & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() ,
FormatDateTime(Fields!FL_DATE.Value, DateFormat.VBShortDate) & Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value).ToString()
, Fields!ATD.Value
, "DataSetAIMS")
).ToString() & " minutes"
However, I think you'd make your life easier by just doing that sort of calculation in the database layer, in the report query, something like:
SELECT
d1.FlightDate
, d1.RegisterNumber
, d1.HealthStartDate
, d2.ATD
, DiffInMinutes = DATEDIFF(MINUTE, d1.HealthStartDate, d2.ATD)
FROM DataSet1 d1
JOIN DataSetAIMS d2
ON CAST(d1.FlightDate AS DATE) = CAST(d2.FL_DATE AS DATE)
AND d1.register_number = d2.REG
AND DATEPART(HOUR, d1.health_start_date) = DATEPART(HOUR, d2.ATD)
This code certainly isn't exact, but hopefully it will get you pointed in the right direction!

Thanks Russel. I have accepted your answer. What I did was to remove the formatdate from the expression code and modify the query design code to convert to the same time date : the code below
=Datediff(DateInterval.Minute, Fields!health_start_date.Value, Lookup(Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() , Fields!REG.Value & DatePart(DateInterval.Hour, Fields!ATD.Value).ToString(), Fields!ATD.Value, "DataSetAIMS") ).ToString() MOD 60 & " mins "
or the below as well works :
=Datediff(DateInterval.Minute,
Fields!health_start_date.Value,
Lookup(
Format(Fields!flight_date.Value, "ddMMyy") & Fields!register_number.Value & DATEPART(DateInterval.Hour,Fields!health_start_date.Value).ToString() ,
Format(Fields!FL_DATE.Value, "ddMMyy") & Fields!REG.Value & DatePart(DateInterval.Hour,Fields!ATD.Value).ToString()
, Fields!ATD.Value
, "DataSetAIMS")
).ToString() MOD 60 & " minutes

Related

Using DCount in Access with multiple criteria

I am trying to count the number of records in a table which satisfy criteria for two different fields. Both fields are string values.
The first field is what type of Test appears e.g. 'Manometry'. I can get this field to work on it's own.
I experience a problem when trying to add the second criteria.
The second field is the TestID, which is in the format A_155_19, where 155 is the investigation number and 19 identifies the year it took place.
I would like to count all the manometry tests which occur in the current year.
DCount("[Test]", "Visits", "[Test] = 'Manometry'" & "[TestID] = *Right((Year(Date)), 2)'")
I am currently getting the error message 3075, which is missing syntax.
Any help would be greatly appreciated.
What about:
DCount("[Test]", "Visits", "[Test] = 'Manometry' And [TestID] Like " & SomeExpression)
You can use Format:
DCount("*", "Visits", "[Test] = 'Manometry' And [TestID] Like '*_' & Format(Date(), "yy") & "'")

Why doesn't this WHERE clause return the right datums?

I'm trying to query a .mdb database, and this is part of the SQL in VB.Net:
sql = sql + "WHERE datdatum BETWEEN #" & "15-10-2018" & "# And #" & "31-10-2018" & "#"
The where clause is working the way you assume. At the moment I change the first date from 15-10-2018 to 01-10-2018, it shows all records from Jan-10 instead of Oct-01.
There are two problems here.
First, don't format the dates that way. Dates used for SQL should always use the ISO8601 format. For date-only values with no time component, there are some reasons to prefer the lesser-known unseparated variant of the standard format, but that's still ISO8601. So the date values should look like this:
sql = sql + "WHERE datdatum BETWEEN #" & "20181015" & "# And #" & "20181031" & "#"
or this:
sql = sql + "WHERE datdatum BETWEEN #" & "2018-10-15" & "# And #" & "2018-10-31" & "#"
Anything else is just begging for the kind of problem in your question, where the actual date read from the string varies based on the culture of the person/device making the interpretation.
This fix might seem to work on it's own, but we still need to do more work because of the 2nd issue:
DON'T USE STRING CONCATENATION TO PUT DATA INTO AN SQL QUERY!
You should always build the query more like this:
sql = sql + " WHERE datdatum BETWEEN ? And ?"
Concatenation is okay, as long as no data, such as a date value, is used. Then you populate the values like this (assuming you have an OleDbCommand object named cmd):
cmd.Parameters.Add("?", OleDbType.Date).Value = DateTime.Parse("2018-10-15")
cmd.Parameters.Add("?", OleDbType.Date).Value = DateTime.Parse("2018-10-31")
This completely avoids the formatting issue from the question, because you're working with .Net DateTime values. It can sometimes run faster (though it may not matter for Access). And it protects against SQL injection issues, both malicious and benign. IMO anything else is amateurish and borders on professional malpractice.

DateDiff not functioning as expected, unable to troubleshoot

I'm trying to set up a query to pull records where the date the record was entered into the database, [AssignmentDate], is compared against today's date, via Now(), to determine whether the record is older than a value selected by the user, e.g. 30 days, 60 days, etc.
Here's the code I have to set a String, SelectionVariables, to the SQL I want:
SelectionVariables = "WHERE (DateDiff('d', [AssignmentDate], Now())>'" & _
CaseAge.Value & _
"');"
Case.Value is the user-selected value from a drop-down. I'm absolutely baffled by the result I get, with Case.Value = 30: the query pulls two records that are dated 6/1/2015 and 5/1/2015, as expected. It does not pull the two records dated 7/15/2015 and 8/1/2015, as expected. It does not pull the record dated 1/1/2015, and for the life of me I cannot diagnose why it isn't getting that one. I haven't found any information indicating that DateDiff has some sort of range that I am exceeding, so I'm left baffled.
Your magical expertise is most appreciated.
HansUp's comment fixed the issue:
What happens if you change your code to this? SelectionVariables = "WHERE >DateDiff('d', [AssignmentDate], Now())>" & CaseAge.Value & ";" – HansUp 24 mins >ago
It appears that the extra parentheses around my original expression were the issue:
(DateDiff('d', [AssignmentDate], Now())>'" & CaseAge.Value & '"');
Not certain why those parentheses cause the expression to evaluate incorrectly, but so it is.

Contains Syntax for SQL

I'm at my wits end here, I'm trying to get this to work
Set rex2 = db.OpenRecordset(" Select count(*) from events where event_date >= #" & Format(last_week_start, "mm/dd/yyyy") & "# and maildate <= #" & Format(last_week_end, "mm/dd/yyyy") & "# and contains(event_type, ""1st call attempted"") and work_ID contains ""UNS"";")
where event_type is the column name in the database and work_ID is also the column name in the database. I've tried it in numerous ways i.e.
WHERE event_type contains ""1st Call Attempted"
etc but I'm having no luck.
I'd change my code but in event_type there are way too many 1st call attempted categories to list.
I'm also open to using a left statement ie
Where left(event_type, 18) = " 1st Call attempted"
Anything to get this sodding thing working
Please help me.
Perhaps you should use the LIKE operator. You'd need to do something like this:
... WHERE event_type LIKE '1st Call attempted%' ...
and similarly for work_ID.
This will match any string that starts with "1st Call attempted" and ends in whatever, since it's like a * wildcard. If you executed it in Access, then you'd use a * instead of a %, but in OLEDB you need to use a %.

Why doesn't my query use my criteria?

I have a db in Access and I'm trying to get a textbox to run my query and pass an other bounded textbox's value in as the criteria in DLookUp. I have the query running in design view and when I enter the criteria directly it returns the correct results. When I open the report it gives me the sum of all the possible rows. In other words it doesn't filter the rows.
I haven't used Access in about twelve years, thankfully, and everything I've done up to this point has been tutorial/example patchwork, but here it is...
SQL Query:
SELECT Sum(IIf(Attended=-1,1,0)) AS attendance
FROM Students_Classes_Attendance
WHERE (((CStr([Students_Classes_Attendance].[Class_Id]))=[classId]));
DLookUp as Control Source:
=DLookUp("[Total Attendance by Class]![attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
I'm lost at the moment. I'm guessing that the value isn't there before the query fires and since the criteria is an optional parameter that it's being passed null, but I would hope you'd get an error from that. Not that #Error is very meaningful anyway.
Does anyone know for certain the problem and the best way to correct it? Thanks.
Edit:
I did the changes recommended in the answer so now my DLookUp looks like...
=DLookUp("[attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
...still returns the total for all rows. Removing the criteria completely makes no difference either, which returns me to thinking it has something to do with the bound textbox not having a value.
DLookup uses the following syntax:
Syntax for numerical values:
DLookup("FieldName" , "TableName" , "Criteria = n")
Syntax for strings: (note the single apostrophe before and after the string value)
DLookup("FieldName" , "TableName" , "Criteria= 'string'")
Syntax for dates: (note the # before and after the date value)
DLookup("FieldName" , "TableName" , "Criteria= #date#")
I believe you just need to remove the table name from the first parameter. Try this:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = " & [Class_Id])
Keep in mind that if Class_Id is a Text Field, you need to surround it by single quotes:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = '" & [Class_Id] & "'")