查询交易

时间:2018-10-30 07:45:47

标签: sql postgresql

我想sum并结成order grandtotal - sum(invoice grandtotal)

这是我的查询

Select 
    co.documentno, co.grandtotal,
    ci.documentno, sum(ci.grandtotal),
    co.grandtotal - sum(ci.grandtotal) as total
From 
    c_order co, c_invoice ci
Where
    co.c_order_id = ci.c_order_id and
    co.docstatus not in ('RE','VO','IN') and
    ci.docstatus not in ('RE','VO','IN')
Group by    
    co.documentno, co.grandtotal,
    ci.documentno, co.c_order_id, ci.c_invoice_id
Order by 
    co.c_order_id, ci.c_invoice_id

我想在发票上显示null,因为订单可以有未清发票,而我的查询没有给我预期的结果

1 个答案:

答案 0 :(得分:0)

您需要加入表以获得空值

    Select 
        co.documentno, co.grandtotal,
        ci.documentno, sum(ci.grandtotal),
        co.grandtotal - sum(ci.grandtotal) as total
    From 
        c_order co
   Left Join
      c_invoice ci
    On
      co.c_order_id = ci.c_order_id
    Where
        co.c_order_id = ci.c_order_id and
        co.docstatus not in ('RE','VO','IN') and
        ci.docstatus not in ('RE','VO','IN')
    Group by    
        co.documentno, co.grandtotal,
        ci.documentno, co.c_order_id, ci.c_invoice_id
    Order by 
        co.c_order_id, ci.c_invoice_id