如果匹配同一表中的值,则更新记录

时间:2013-01-30 14:30:03

标签: sql ms-access access-vba

我有一个包含交易列表的MS Access数据库。我正在尝试更新两个记录中的“匹配”字段,它们在字段(文档编号,凭证编号,子标题)中具有一些相同的值,但数量相反。它还需要避免重复。

    Document Number     Amount   ABS     Match
    N6809561990112      438.48   438.48
    N6809561990112      438.48   438.48
    N6809561990112     -438.48   438.48

SQL之后的最终结果应该是什么

    Document Number     Amount   ABS     Match
    N6809561990112      438.48   438.48   Y
    N6809561990112      438.48   438.48
    N6809561990112     -438.48   438.48   Y

表名是“tblUnmatched”

我尝试了以下内容,但它将表格中的每条记录更新为“Y”

strSql = "Update tblUnmatched SET match = 'Y' WHERE EXISTS(select * " & _
        "from tblUnmatched t1 " & _
        "inner join tblUnmatched t2 on " & _
        "t1.[DOCUMENT NUMBER] = t2.[DOCUMENT NUMBER]" & _
        "where t1.ABS = t2.ABS AND t1.AMOUNT <> t2.AMOUNT AND t1.SUBH = t2.SUBH)"
DoCmd.RunSQL strSql

我也尝试了这个,但它无法处理重复的问题。

strSql = "Update tblUnmatched SET match = 'Y' WHERE [DOCUMENT NUMBER] IN(select t1.[DOCUMENT NUMBER] " & _
        "from tblUnmatched t1 " & _
        "inner join tblUnmatched t2 on " & _
        "t1.[DOCUMENT NUMBER] = t2.[DOCUMENT NUMBER]" & _
        "where t1.ABS = t2.ABS AND t1.AMOUNT <> t2.AMOUNT AND t1.SUBH = t2.SUBH)"
    DoCmd.RunSQL strSql

1 个答案:

答案 0 :(得分:1)

在没有主键字段的Access SQL中,您的任务不切实际。虽然您导入的数据源中没有此类密钥,但这并不禁止您在Access中添加密钥。

将自动编号主键id添加到tblUnmatched。然后为每批新的传入数据:

  1. 导入临时表tblScratch
  2. DELETE FROM tblUnmatched
  3. tblScratch中的行追加到tblUnmatched
  4. (如果您可以使用SELECT FROM <your data source>直接附加到tblUnmatched,而不是先导入tblScratch,则此过程可能会更清晰。)

    将以下SELECT语句保存为qryFindMatches

    SELECT
        sub.[Document Number],
        sub.Amount,
        sub.MinOfid,
        DCount(
            "*",
            "tblUnmatched",
            "[Document Number]='" & [Document Number]
                & "' AND Amount = -1 * " & [Amount]
            ) AS match_count
    FROM
        (
            SELECT [Document Number], Amount, Min(id) AS MinOfid
            FROM tblUnmatched
            GROUP BY [Document Number], Amount
        ) AS sub;
    

    然后您想要的UPDATE可以相当容易地创建。注意性能可能不是很快;希望你能每月容纳一次。

    UPDATE tblUnmatched
    SET [Match] = True
    WHERE id In
        (
            SELECT MinOfId
            FROM qryFindMatches
            WHERE match_count > 0
        );
    

    我在您的示例数据中添加了一行,并使用Access 2007进行了测试。我认为这就是您想要的...

    id Document Number Amount   Match
     1 N6809561990112   $438.48 True
     2 N6809561990112   $438.48 False
     3 N6809561990112 ($438.48) True
     4 N6809561990112     $5.00 False