如何确保在连接表中有多于1个匹配的条目,它在第一个可能的条目上只匹配一次 .

我尝试在 "transactionDate""transactionAmount" 上将一张独特的信用卡付款表添加到发票表中

它可以工作 creditcard_table LEFT JOIN invoice_table ,但是我希望每张发票加上匹配的信用卡付款,所以基本上 creditcard_table RIGHT JOIN invoice_table . 问题是每天通常有超过1张发票,金额完全相同 .

我最后创建了一个带有 creditcard_table RIGHT JOIN invoice_table 的视图,其中包含相同信用卡付款的每个唯一发票,而不是在第二个视图的加入语句中使用此视图与DISTINCT ON(creditcard_payment) .

它工作得很好,除了信用卡付款的ID与发票表中除第一个之外的第二个可能条目不匹配 .

第一视图 creditcard_table RIGHT JOIN invoice_table

CREATE VIEW "2016"."2" AS SELECT DISTINCT ON (belege."belegID") belege."belegID",
    belege."rechNum",
    cap."slipNr",
    belege."rechDate",
    cap."transactionDate",
    belege."rechSum",
    cap."transactionAmount"
   FROM ("2016".belege
     LEFT JOIN "2016".cap ON (((belege."rechDate" = cap."transactionDate") 
        AND (belege."rechSum" = cap."transactionAmount"))))
      ORDER BY belege."belegID";

结果:

belegID | rechNum | slipNr |  rechDate  | transactionDate | rechSum | transactionAmount
---------+---------+--------+------------+-----------------+---------+-------------------
       1 |    2230 |   6196 | 2016-01-02 | 2016-01-02      |  234.30 |            234.30
       2 |    2231 |        | 2016-01-02 |                 |  148.30 |
       3 |    2232 |   6197 | 2016-01-02 | 2016-01-02      |   69.90 |             69.90
       4 |    2233 |        | 2016-01-02 |                 |   74.50 |
       5 |    2234 |   6198 | 2016-01-02 | 2016-01-02      |  106.80 |            106.80
       6 |    2235 |   6199 | 2016-01-02 | 2016-01-02      |   54.80 |             54.80
       7 |    2236 |   6201 | 2016-01-04 | 2016-01-04      |   41.00 |             41.00
       8 |    2237 |   6201 | 2016-01-04 | 2016-01-04      |   41.00 |             41.00
       9 |    2238 |   6202 | 2016-01-04 | 2016-01-04      |   55.40 |             55.40

我在此查询中使用该视图“2”:

CREATE VIEW "2016"."3" AS SELECT belege."belegID",
    belege."rechNum",
    belege."rechDate",
    belege."rechSum",
    cap."slipNr",
    cap."transactionDate",
    cap."transactionAmount",
    cap."batchTotal"
   FROM (("2016".belege
     LEFT JOIN ( SELECT DISTINCT ON (zwei."slipNr") zwei."belegID",
            zwei."slipNr"
           FROM "2016"."2" zwei
          ORDER BY zwei."slipNr") two ON ((belege."belegID" = two."belegID")))
     LEFT JOIN "2016".cap ON ((cap."slipNr" = two."slipNr")))
  ORDER BY belege."belegID", two."slipNr";

结果:

rechNum |  rechDate  | rechSum | slipNr
---------+------------+---------+--------
    2230 | 2016-01-02 |  234.30 |   6196
    2231 | 2016-01-02 |  148.30 |
    2232 | 2016-01-02 |   69.90 |   6197
    2233 | 2016-01-02 |   74.50 |
    2234 | 2016-01-02 |  106.80 |   6198
    2235 | 2016-01-02 |   54.80 |   6199
    2236 | 2016-01-04 |   41.00 |
    2237 | 2016-01-04 |   41.00 |   6201
    2238 | 2016-01-04 |   55.40 |   6202

正如您在1月4日的第一张表中所看到的,每个41.00有两笔付款,因此信用卡付款6201被插入两次 . 通过第二个查询,我尝试将信用卡付款与仅一张发票相匹配 . 为什么记录没有插入 rechNum 2236,这将是第一个匹配的记录 . 如果可能的话,您如何将查询更改为一个,以提供预期的结果 .