-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

テーブルを結合したら、COALESCEorを使用して、注文のない顧客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

デモで SQL Fiddle を参照してください

于 2013-02-27T14:43:21.163 に答える