努力编写查询以获取所需信息。见下文:
表客户
CustId CustName
1 Andy
2 Rob
3 Craig
4 Rashi
表客户订单
CustId OrderQuantity
1 3
2 5
3 10
1 2
需要输出:
CustId CustName NumberofOrdersPlaced
1 Andy 5
2 Rob 5
3 Craig 10
4 Rashi 0
如果Customer
未下订单,则NumberofOrdersPlaced
应设为0.
我正在努力解决这个简单的问题。请有人帮忙。
答案 0 :(得分:1)
select
c.custid,
c.custname,
co.sum(orderquantity) as NumberofOrdersPlaced
from customers c
left join customer_orders co on c.custid = co.custid
group by custid,custname
答案 1 :(得分:0)
select c.custId
,c.custName
,(select count(1) from CustomerOrders where custId = c.custId) numberoforders
from Customers c
答案 2 :(得分:0)
您只需在表格上使用LEFT JOIN
即可。即使LEFT JOIN
表中没有匹配的行,customers
也会返回customer_orders
表中的所有行。
加入表后,您可以使用COALESCE
或IsNull
将null
值替换为零,以便那些没有订单的客户:
select
c.custid,
c.custname,
coalesce(sum(co.orderquantity), 0) as NumberofOrdersPlaced
from customers c
left join customer_orders co
on c.custid = co.custid
group by c.custid, c.custname
order by c.custid