【问题标题】:show the customer who had the highest order amount in Northwind database显示罗斯文数据库中订单金额最高的客户
【发布时间】:2018-12-22 14:53:26
【问题描述】:

我正在使用 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 函数将其链接到区域。

【问题讨论】:

  • 你不能用TOP 1ORDER BY ValueOfOrders DESC吗?

标签: sql sql-server tsql subquery northwind


【解决方案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 或 SubQuery 来获取 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

【讨论】:

  • 它有效,现在它显示每个区域的最大数量。我如何才能查看下订单的客户的姓名?当我尝试将它添加到分组时它不起作用(我使用最大解决方案)
  • @TheTwo 只有第一个解决方案(使用TOP 1)可以显示客户名称,MAX 解决方案不能。只需在第一个查询的SELECT 子句中添加CustomerID 即可。
【解决方案2】:

懒惰的做法

;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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2019-09-13
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2014-04-20
      相关资源
      最近更新 更多