显示在Northwind数据库中拥有最高订单金额的客户

时间:2018-12-22 14:53:27

标签: sql sql-server tsql subquery northwind

我正在使用罗斯文(Northwind)数据库,并且需要针对每个地区向客户显示订单量最高的客户

我的桌子是:

-- Customers --   
[CustomerID] [nchar](5) NOT NULL,    
[CompanyName] [nvarchar](40) NOT NULL,   
[ContactName] [nvarchar](30) NULL,    
[ContactTitle] [nvarchar](30) NULL,    
[Address] [nvarchar](60) NULL,  
[City] [nvarchar](15) NULL,    
[Region] [nvarchar](15) NULL,    
[PostalCode] [nvarchar](10) NULL,   
[Country] [nvarchar](15) NULL,   
[Phone] [nvarchar](24) NULL,    
[Fax] [nvarchar](24) NULL,

--OrderDetails
[OrderID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[UnitPrice] [money] NOT NULL,
[Quantity] [smallint] NOT NULL,
[Discount] [real] NOT NULL,
CONSTRAINT [PK_Order_Details] PRIMARY KEY CLUSTERED

-- Orders
[OrderID] [int] IDENTITY(1,1) NOT NULL,
[CustomerID] [nchar](5) NOT NULL,
[EmployeeID] [int] NULL,
[OrderDate] [datetime] NULL,
[RequiredDate] [datetime] NULL,
[ShippedDate] [datetime] NULL,
[ShipVia] [int] NULL,
[Freight] [money] NULL,
[ShipName] [nvarchar](40) NULL,
[ShipAddress] [nvarchar](60) NULL,
[ShipCity] [nvarchar](15) NULL,
[ShipRegion] [nvarchar](15) NULL,  
[ShipPostalCode] [nvarchar](10) NULL,
[ShipCountry] [nvarchar](15) NULL,
CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED   

我首先尝试为每个客户计算总金额

select 
    sum(unitprice * quantity * 1+Discount) as ValueOfOrders
from 
    OrderDetails od 
join 
    orders o on od.OrderID = o.OrderID 
group by 
    CustomerID

但是我不知道如何使用max函数将其链接到区域。

3 个答案:

答案 0 :(得分:1)

怎么样

select TOP 1
    sum(unitprice * quantity * (1+Discount)) as ValueOfOrders
from 
    OrderDetails od 
join 
    orders o on od.OrderID = o.OrderID 
group by 
    CustomerID
ORDER BY ValueOfOrders DESC;

或者甚至通过使用CTE或子查询来获取MAX()

SELECT MAX(ValueOfOrders) ValueOfOrders
FROM
(
select 
    sum(unitprice * quantity * 1+Discount) as ValueOfOrders
from 
    OrderDetails od 
join 
    orders o on od.OrderID = o.OrderID 
group by 
    CustomerID
) T

答案 1 :(得分:0)

懒惰的方式

;WITH totals AS
(
select  c.Region, o.CustomerID, 
        SUM(unitprice * quantity * 1+Discount) AS Total
from [Order Details] od 
join orders o on od.OrderID = o.OrderID 
join Customers c on c.CustomerID = o.CustomerID
group by c.Region, o.CustomerID
)
, byRegion AS
(
select *, 
    ROW_NUMBER() OVER(PARTITION BY Region ORDER BY Total DESC) as rn 
from totals

)

select *
from byRegion 
where rn = 1
order by Region

答案 2 :(得分:-1)

使用NorthWind数据库,查看所有运费最高且付款方式为信用卡的客户。