首先,找出每個客戶訂購了多少項目。要做到這一點,你必須加入訂單的詳細信息及訂單表:
select o.customerid, sum(od.quantity) as nbr_items
from orderdetail od
inner join orders o
on o.orderid = od.orderid
group by o.customerid
但是如果你需要客戶名稱爲好,這是相當有可能的,你就必須加入customer表,太:
select o.customerid, sum(od.quantity) as nbr_items
from orderdetail od
inner join orders o
on o.orderid = od.orderid
inner join customer c
on c.customerid = o.customerid
group by o.customerid
不過,當然,你的項目的最總金額特別要求的客戶,由總讓降序排序:
select o.customerid, sum(od.quantity) as nbr_items
from orderdetail od
inner join orders o
on o.orderid = od.orderid
inner join customer c
on c.customerid = o.customerid
group by o.customerid
order by 2 DESC
,並使用TOP N函數只得到第一種:
select top 1 o.customerid, sum(od.quantity) as nbr_items
from orderdetail od
inner join orders o
on o.orderid = od.orderid
inner join customer c
on c.customerid = o.customerid
group by o.customerid
order by 2 DESC
來源
2014-05-13 14:12:46
MJB
當提出這樣的問題時,有助於說「這是我處理的表格佈局」和「這是我期望得到的迴應類型」。儘管我們知道Northwind數據庫,但我們並不記住結構。 – MJB
將在底部發布修訂版本! – user3629590