Access - Get latest date if column contains value from another one

北战南征 提交于 2020-02-06 08:45:29

问题


I'm having an issue with a VBA function for my query in Access.
I have a table "tbldata"

Equipment   Last Inspection
420-413     2019-06-15
440-433     2019-06-15
402-483     2019-06-29
420-413     2019-12-12

and a query "qryunpair"

UnpairEquipment
420 
413 
440 
433 
402 
483 

What I'm trying to achieve is:

Equipment Latest Date
420       2019-12-12
413       2019-12-12
440       2019-06-15
433       2019-06-15
402       2019-06-29
483       2019-06-29

I've made the following code, but when I ran it, it didn't return any values. Is there a solution to this?

Function typeinspection(Source As String) As String
Dim Rst As Recordset
Dim Rst2 As Recordset
Dim s As String
    s = ""
    Set Rst = CurrentDb.OpenRecordset("tbldata")
    Set Rst2 = CurrentDb.OpenRecordset("qryunpair")
    While Not Rst.EOF

        If InStr(Source, Rst2.Fields("UnpairEquipment") > 0) Then _
            s = Rst.Fields("Last Inspection")
        Rst.MoveNext
    Wend

    Set Rst = Nothing
    Set Rst2 = Nothing
    typeinspection = s

End Function

回答1:


If you want a query that returns your expected results, you can join the table and the query with the use of the operator LIKE:

SELECT q.UnpairEquipment AS Equipment, MAX([Last Inspection]) AS [Latest Date]
FROM qryunpair AS q INNER JOIN tbldata AS t
ON '-' + t.Equipment + '-' LIKE '*-' +  q.UnpairEquipment + '-*'
GROUP BY q.UnpairEquipment

Results:

Equipment   Latest Date
402         2019-06-29
413         2019-12-12
420         2019-12-12
433         2019-06-15
440         2019-06-15
483         2019-06-29


来源:https://stackoverflow.com/questions/59376908/access-get-latest-date-if-column-contains-value-from-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!