-1

努力编写查询以获取所需的信息。见下文:

客户

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 

如果 aCustomer没有下任何订单,则NumberofOrdersPlaced应该设置为 0。

我正在为这个简单的查询而苦苦挣扎。请有人帮忙。

4

3 回答 3

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
于 2013-02-27T13:18:16.887 回答
0
select c.custId
   ,c.custName
   ,(select count(1) from CustomerOrders where custId = c.custId) numberoforders
   from Customers c
于 2013-02-27T13:18:55.190 回答
0

你只需要LEFT JOIN在桌子上使用 a 。即使表中没有匹配的行,也会返回表中LEFT JOIN的所有行。customerscustomer_orders

加入表格后,对于没有订单的客户,您可以使用COALESCEIsNull将值替换为零: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

请参阅带有演示的 SQL Fiddle

于 2013-02-27T14:43:21.163 回答