【问题标题】:how to get the last non empty column in ms access如何在 ms 访问中获取最后一个非空列
【发布时间】:2021-07-17 15:57:59
【问题描述】:

所以我有一个庞大的数据库用于我的学校项目,它是这样的

id team game1 score1 game2 score2 game3 score3
1 barca vs real 2-1 vs bvb 5-2 vs atletic 0-3
2 real madrid vs barca 1-2 vs betis 3-0
3 man city vs man united 1-2

并且我想查询只会给我每支球队的最后一场比赛 在 excel 中它很容易,但我不能在 ms 访问中做到这一点 我需要的结果是

id team last game
1 barca vs atletic
2 real madrid vs betis
3 man city vs man united

【问题讨论】:

    标签: sql vba database ms-access


    【解决方案1】:

    已经评论过的一件事是您的数据库设计需要修复 - 您不会遍历(就像在 Excel 中那样),而是作为表格中的额外行向下遍历。您需要注意的 Access 表中有 255 个字段的限制。

    但是,如果您决定坚持这一点,另一种解决方法是创建一个小的 VBA 函数,该函数将字段向后循环以获得您需要的答案。比如:

    Function fLastMatch(lngTeamID As Long) As String
        On Error GoTo E_Handle
        Dim db As DAO.Database
        Dim rs As DAO.Recordset
        Dim strSQL As String
        Dim lngLoop1 As Long
        Set db = DBEngine(0)(0)
        strSQL = "SELECT * FROM tblFootball WHERE id=" & lngTeamID
        Set rs = db.OpenRecordset(strSQL)
        If Not (rs.BOF And rs.EOF) Then
            For lngLoop1 = rs.Fields.Count - 2 To 2 Step -2
                If Not IsNull(rs.Fields(lngLoop1)) Then
                    fLastMatch = rs.Fields(lngLoop1)
                    Exit For
                End If
            Next lngLoop1
        End If
    fExit:
        On Error Resume Next
        rs.Close
        Set rs = Nothing
        Set db = Nothing
        Exit Function
    E_Handle:
        MsgBox Err.Description & vbCrLf & vbCrLf & "fLastMatch", vbOKOnly + vbCritical, "Error: " & Err.Number
        Resume fExit
    End Function
    

    这是有效的,因为记录集中的最后一个(nth)字段是位置 n-1,因为记录集是 0 索引的(第一个字段位于位置 0,第二个字段是位置 1 .....)。这意味着最后一个匹配字段在位置 n-2。所以我们从字段中的这个位置开始,检查是否有数据。如果有,我们已经找到了最后一场比赛并且可以退出循环。如果没有数据,那么我们返回两个字段,到上一个匹配,然后重复检查。

    然后您可以在查询中使用此函数来获得您需要的答案:

    SELECT id, fLastMatch(id) AS LastMatch
    FROM tblFootball;
    

    这种方法意味着您无需担心包含多少匹配项,并且如果随着时间的推移会发生变化(这在数据库中是个坏主意),则可以添加正确数量的 Nzs。

    问候,

    【讨论】:

    • sooooo 我试图理解这个(不要误会我的意思,它就像魔术一样)谢谢你
    • 我已经编辑了答案,包括解释代码的核心部分在做什么以及为什么。
    【解决方案2】:

    假设缺失值为null,可以使用nz()

    select id, team,
           nz(game3, nz(game2, game1)) as last_game
    from t;
    

    请注意,这在任何其他数据库中都会更简单。标准 SQL 函数 coalesce() 接受多个参数:

    select id, team,
           coalesce(game3, game2, game1) as last_game
    from t;
    

    【讨论】:

    • 如果表不包含每个游戏的两个字段会简单得多,但这可能是对数据库的完全重新设计。
    • 所以我得到的是 'nz()' 函数只使用两个参数,我有大约 15 场比赛,我认为这有点不可能,我不能在 ms 访问中使用 'COALESCE()'。我能找到另一种解决方法吗?
    • @Simoh。 . .继续嵌套nz()s。
    • @DarrenBartrup-Cook 。 . .可能是。也许不吧。毕竟这是 MS Access。
    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多