SQL Server - 连接两个表来获取数据

时间:2013-02-27 13:15:51

标签: sql sql-server

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

客户

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.

我正在努力解决这个简单的问题。请有人帮忙。

3 个答案:

答案 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表中的所有行。

加入表后,您可以使用COALESCEIsNullnull值替换为零,以便那些没有订单的客户:

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 with Demo