某些制造商的客户支出总额,包括$ 0

时间:2014-11-04 03:09:45

标签: sql join sum

我有一个SQL数据库,其中包含三个相应的表,客户,订单和项目。客户的ID与订单中的ID相对应。订单的订单号对应于商品中的一个。项目是包含客户在特定公司花费的金额的表格。在这种情况下,我想总结在一家名为“HRO”的公司所花费的总金额,包括那些没有在HRO消费的客户(他们名字旁边的零)。我有这个工作正常,除了包括零部分。提前谢谢!

select customer.customer_num, customer.fname, sum(items.total_price) amountSpent
from customer
    left join orders
        on customer.customer_num = orders.customer_num
    left join items
        on orders.order_num = items.order_num
where items.manu_code like 'HRO'
group by customer.customer_num, customer.fname

1 个答案:

答案 0 :(得分:3)

您的where items.manu_code like 'HRO'条款不包括那些没有订单的客户,因为这些客户'对于null,行将有items.manu_code

尝试将该过滤器移动到连接中而不是where子句:

select 
     customer.customer_num, customer.fname, 
     isnull(sum(items.total_price),0) amountSpent
from customer
    left join orders
        on customer.customer_num = orders.customer_num
    left join items
        on orders.order_num = items.order_num 
       and items.manu_code like 'HRO'
group by customer.customer_num, customer.fname

我已将sum包裹在isnull中,以便没有订单的客户显示为零消费而非花费null