簡體   English   中英

如果同一表中的值匹配,則更新記錄

[英]Update record if matching values in same table

我有一個帶有事務列表的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

在沒有主鍵字段的Access SQL中,您的任務不切實際。 盡管您導入的數據源中沒有這樣的密鑰,但這並不能阻止您在Access中添加密鑰。

將自動編號主鍵id添加到tblUnmatched 然后,對於每一批新的傳入數據:

  1. 導入到臨時表tblScratch
  2. DELETE FROM tblUnmatched
  3. tblScratch的行附加到tblUnmatched

(如果可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM