使用2个表加入查询

时间:2009-11-26 05:27:33

标签: sql-server

SELECT 
PB_BANK_CODE,    ---- DB ITEM
PB_BANK_NAME,  ---- DB ITEM
TOTAL_AMOUNT   --- NON DB ITEM
        FROM    GLAS_PDC_BANKS          

where PB_COMP_CODE=:parameter.COMP_CODE AND  pb_bank_code in(select distinct pc_bank_from from glas_pdc_cheques where PC_COMP_CODE=:parameter.COMP_CODE AND pc_due_dateTIME between :block01.date_from and :block01.date_to AND ISNULL(pc_discd,'X') = 'R')
order by pb_bank_code

总金额:

BEGIN
  SELECT SUM(PC_AMOUNT) INTO :BLOCK02.TOTAL_AMOUNT
    FROM GLAS_PDC_CHEQUES
   WHERE PC_DUE_DATE BETWEEN :BLOCK01.DATE_FROM AND :BLOCK01.DATE_TO
     AND   PC_BANK_FROM = :BLOCK02.PB_BANK_CODE
     AND   NVL(PC_DISCD, 'X') = 'R';
EXCEPTION WHEN OTHERS THEN :BLOCK02.TOTAL_AMOUNT := 0;
END;

也应该显示总额。

如何加入上述两个选择语句

1 个答案:

答案 0 :(得分:1)

使用:

   SELECT b.pb_bank_code,
          b.pb.bank_name,
          b.total_amount,
          COALESCE(x.sum_amount, 0)
     FROM GLAS_PDC_BANKS b
LEFT JOIN (SELECT c.pc_bank_from,
                  SUM(c.pc_amount) 'sum_amount'
             FROM GLAS_PDC_CHEQUES c
            WHERE c.pb_comp_code = :parameter.COMP_CODE
              AND c.pc_due_date BETWEEN :block01.date_from AND :block01.date_to 
              AND c.pc_discd = 'R'
         GROUP BY c.pc_bank_from) x ON x.pc_bank_from = b.pb_bank_code

我省略了:

NVL(PC_DISCD, 'X') = 'R';  --Oracle syntax btw
ISNULL(pc_discd,'X') = 'R'

如果它不是你想要的那个,那么将空值转换为x是没有意义的。