SQL如何连接两个表而不重复

时间:2016-05-31 11:31:30

标签: sql join

我有这两张桌子。我正在尝试获取item_tbl中的金额,但payment_dt位于另一个表格中(payment_tbl)。

如何加入这两张桌子并正确获取金额?现在,我的SQL(使用PostgreSQL)生成3行,所以当我得到总和时,数量乘以3。

item_tbl

receipt_no | gross_amount | other_discount_amount | net_of_discount_amount 
0000000617 |      2000.00 |                400.00 |                1600.00

payment_tbl

receipt_no | amount(net) | payment_method | payment_dt
0000000617 |      639.49 | cash           | 2016-05-31 11:48:23.5+08
0000000617 |      500.00 | check          | 2016-05-31 11:48:23.5+08
0000000617 |      500.00 | debit card     | 2016-05-31 11:48:23.5+08

预期结果

gross_amount | other_discount_amount | net_of_discount_amount 
2000.00      |                400.00 |                1600.00

查询:

SELECT
    cashier.cashier_name,
    COALESCE(gross_amount, 0) AS gross_amount,
    (CASE WHEN item.other_discount_type = 'OTHER' THEN COALESCE(item.other_discount_amount, 0) ELSE 0 END) AS other_discount_amount,
    COALESCE(item.net_of_discount_amount, 0) AS net_of_discount_amount
FROM 
    item_tbl item
INNER JOIN 
    payment_tbl payment ON item.receipt_no = payment.receipt_no
LEFT JOIN 
    cashier_tbl cashier ON cashier.id = item.cashier_id
WHERE 
    date(payment.payment_dt) = to_date('31 May 2016', 'dd Mon YYYY')

1 个答案:

答案 0 :(得分:0)

特定收据的所有付款记录必须具有相同的日期时间才能正常工作。

SELECT
    cashier.cashier_name,
    COALESCE(gross_amount, 0) AS gross_amount,
    (CASE WHEN item.other_discount_type = 'PATRONAGE_CASH' THEN COALESCE(item.other_discount_amount, 0) ELSE 0 END) AS other_discount_amount,
    COALESCE(item.net_of_discount_amount, 0) AS net_of_discount_amount
FROM item_tbl item
    INNER JOIN (Select receipt_no, Max(payment_dt) payment_dt from payment_tbl Group By receipt_no) payment ON item.receipt_no = payment.receipt_no
    LEFT JOIN cashier_tbl cashier ON cashier.id = item.cashier_id
WHERE 
    AND date(payment.payment_dt) = to_date('31 May 2016', 'dd Mon YYYY')