2016-05-31 3 views
-1

나는이 두 테이블을 가지고있다. item_tbl에서 금액을 받으려고하지만 payment_dt은 다른 테이블에 있습니다 (payment_tbl).SQL 중복 테이블없이 두 테이블을 결합하는 방법

두 테이블을 결합하여 금액을 올바르게 계산하려면 어떻게해야합니까? 지금 당장, 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') 
+4

어느 정도의 금액이 필요합니까? 예상 결과를 추가하십시오 – Jens

+1

어떤 DBMS를 사용하고 있습니까? 관련이 없지만 : to_date ('2011 5 월 31 일 ','dd Mon YYYY ')를 사용한 변환은 현재 환경에 의존합니다. 예를 들어 내 컴퓨터에서 작동하지 않습니다. 언어에 의존하지 않는 날짜 값을 사용해야합니다 (예 : '31-05-2016' –

+0

구문 오류입니다. (힌트 : where 절.) – jarlh

답변

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') 
관련 문제