每行发票余额

时间:2016-04-15 05:37:32

标签: sql oracle

请参阅下面的代码以及结果和预期结果

 SELECT 
    DISTINCT VW_PM_INV_BAL.invoice_no,                      
    VW_PM_INV_BAL.quote_section_id , 
    paymatic_debtors_info.type, 
    cl$invoices.total INVOICED_AMT, 
    paymatic_debtors_info.amount PAID_CR_REV 
 FROM 
    paymatic_debtors_info 
 left outer JOIN cl$invoices 
    ON cl$invoices.invoice_no = paymatic_debtors_info.ref 
 left outer JOIN VW_PM_INV_BAL 
    ON VW_PM_INV_BAL.invoice_no = cl$invoices.invoice_no 
 WHERE 
   VW_PM_INV_BAL.quote_section_id = '1000065052' 
 ORDER BY 1, 2 DESC;

结果

Invoice_no  Quote_section_id   Type   Invoiced   Paid_CR_REV 
729001      1000065052         Inv      70680       70680 
729001      1000065052         Pmt      70680      -70680 
732331      1000065052         Inv      21556.26    21556.26 
732331      1000065052         Pmt      21556.26   -21556.26 
751231      1000065052         Inv      21556.374   21556.37 
751231      1000065052         Pmt      21556.374   -21556.37 
753107      1000065052         Inv      21556.374   21556.37 
753107      1000065052         Pmt      21556.374   -21556.37 
753107      1000065052         Rev      21556.374   21556.37

预期

Invoice_no   Quote_section_id Type Invoiced Paid_CR_REV Balance 
729001       1000065052       Inv   70680
729001       1000065052       Pmt           -70680           0 
732331       1000065052       Inv   21556.26
732331       1000065052       Pmt           -21556.26        0 
751231       1000065052       Inv   21556.374
751231       1000065052       Pmt           -21556.37        0 
753107       1000065052       Inv   21556.374
753107       1000065052       Pmt           -21556.37        0 
753107       1000065052       Rev   21556.374                21556.374

1 个答案:

答案 0 :(得分:0)

所以,

  • 表示要显示已开票的'Inv'行,但不包括Paid_CR_REV和Balance。
  • 对于'Pmt'行,您要显示Paid_CR_REV和Invoiced + Paid_CR_REV作为余额,但不是已开票。
  • 表示您想要显示两次发票的'Rev'行,一次显示为已开票,一次为余额且没有Paid_CR_REV。

相应地使用CASE WHEN

select
  bal.invoice_no,
  bal.quote_section_id ,
  pdi.type,
  case when pdi.type in ('Inv', 'Rev') then inv.total end as invoiced,
  case when pdi.type = 'Pmt' then pdi.amount end as paid_cr_rev,
  case when pdi.type = 'Pmt' then inv.total + pdi.amount
       when pdi.type = 'Rev' then inv.total end as balance
from paymatic_debtors_info pdi
join cl$invoices inv on inv.invoice_no = pdi.ref
join vw_pm_inv_bal bal on bal.invoice_no = inv.invoice_no
where bal.quote_section_id = '1000065052'
order by 1, 2 desc;

至少这是我从你所展示的内容中收集的内容。您并没有真正提出问题,也没有告诉我们您的表格以及如何计算结果。因此,您可能仍需要稍微调整以上查询。

我认为你不需要DISTINCT,所以我删除了它。如果你确实需要,请把它放回去。 (或者重写查询,不要这样做。)

我认为你不需要外连接(在你显示的结果中至少所有记录都存在),所以我也删除了这些。