【问题标题】:Summing total of foreign key relationship and dealing with null外键关系总和并处理空值
【发布时间】:2019-04-16 00:00:05
【问题描述】:

我有一个查询,它计算我的收据中的项目并返回它们的数据以生成报告。我有一些项目被退回的情况,因此在获取此数据时,我必须通过使用 return_item_id 获取所有操作来考虑这一点。

物品表:
身份证
名字

操作表:
return_item_id
金额

ReceiptItem 表:
item_id
价格
金额

select
cps_item.name as "item.name",
ROW_NUMBER () OVER (ORDER BY e.create_ts) as "row",
e.amount - SUM(cps_operation.amount) as "amount",
e.price as "price",
e.amount * e.price as "sum"
from cps_receipt_items e  
left join cps_item ON e.item_id = cps_item.code
left join cps_operation ON e.id = cps_operation.return_item_id
where e.receipt_id = ${sell}
and e.item_id is not null
group by cps_item.name, e.amount, e.price, e.create_ts;

我想要的预期结果是正确显示所有金额,但是当 SUM(cps_operation.amount) 返回 Null 时会发生什么,因为没有返回操作它返回空值,而不是只显示没有 SUM 结果的金额( cps_operation.amount)。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    使用合并

    select
    cps_item.name as "item.name",
    ROW_NUMBER () OVER (ORDER BY e.create_ts) as "row",
    e.amount - coalesce(SUM(cps_operation.amount),0) as "amount",
    e.price as "price",
    e.amount * e.price as "sum"
    from cps_receipt_items e  
    left join cps_item ON e.item_id = cps_item.code
    left join cps_operation ON e.id = cps_operation.return_item_id
    where e.receipt_id = ${sell}
    and e.item_id is not null
    group by cps_item.name, e.amount, e.price, e.create_ts;
    

    【讨论】:

    • 谢谢你的作品我想知道是否有可能在我可以使用这个结果的地方只返回大于 0
    猜你喜欢
    • 2016-10-11
    • 2013-05-27
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多