SQL Server-连接两个表以获取数据
正在努力编写查询以获取所需信息。见下文: 表客户SQL Server-连接两个表以获取数据,sql,sql-server,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 1 Andy 2 Rob 3 Craig 4 Ras
CustId CustName
1 Andy
2 Rob
3 Craig
4 Rashi
CustId OrderQuantity
1 3
2 5
3 10
1 2
表客户订单
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
如果客户
没有下任何订单,则NumberofOrdersPlaced
应设置为0
我正在努力解决这个简单的问题。请找人帮忙。您只需在表上使用
左连接即可。LEFT JOIN
将返回customers
表中的所有行,即使customer\u orders
表中没有匹配的行
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
加入表后,对于没有订单的客户,可以使用或将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
请参见您已经尝试了什么?即使没有订单,每个客户在场的要求是否表明您有特定类型的加入?