2013-02-27 26 views
-1

努力编写查询来获取所需的信息。请看下图:SQL Server - 连接两个表来获取数据

客户

CustId CustName 
1  Andy 
2  Rob 
3  Craig 
4  Rashi 

客户订单要求

CustId OrderQuantity 
1  3 
2  5 
3  10 
1  2 

OUTPUT:

CustId CustName  NumberofOrdersPlaced 
1  Andy     5 
2  Rob     5 
3  Craig    10 
4  Rashi     0 

如果Customer还没有PL任何订单,NumberofOrdersPlaced应该设置为0.

我正在努力与这个简单的查询。请有人帮忙。

+1

你有什么已经尝试过?即使没有订单,每个客户的要求是否存在,都表明您有特定类型的加盟? – 2013-02-27 13:18:00

回答

0
select c.custId 
    ,c.custName 
    ,(select count(1) from CustomerOrders where custId = c.custId) numberoforders 
    from Customers c 
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 
0

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

一旦你连接的表,那么你可以使用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 with Demo

相关问题