使用带 SQL 服务器的 Northwind 数据库在三个表之间进行子查询

Subquery between three tables using Northwind database with SQL Server

  1. Table [Orders] : OrderID(Primary Key), CustomerID
  2. Table [Order Details] : OrderID(Primary Key), ProductID(Primary Key), Discount
  3. Table [Customers] : CustomerID[Primary Key]

对于这三个表,我想查询每个 CustomerID 的折扣最高的 productID。我需要 ProductIDCustomerIDDiscount 的列。我怎么解决这个问题?非常感谢各种帮助。

我试过以下脚本:

select ProductID, a.customerID, 
    (select MAX(discount) 
     from [Order Details] 
     where a.CustomerID=c.customerID
    )
from Orders a 
    join [Order Details]
        on a.OrderID=[Order Details].OrderID 
    join Customers c
        on a.CustomerID=c.CustomerID    
order by customerID

下面的查询会return给你每个客户最大折扣的productid。请注意,如果对于特定客户,您有不止一种可能有最大折扣的产品,我想 return 他们,那么您需要将 ROW_NUMBER() 替换为 DENSE_RANK()

  WITH CTE AS 
    (SELECT ProductID, 
           o.CustomerID,
           Discount,
           ROW_NUMBER() OVER(PARTITION BY o.CustomerID ORDER BY Discount DESC) Row_num
    FROM [Order Details] od INNER JOIN Orders o
         ON od.OrderID= o.OrderID
    )
    SELECT ProductID, 
           CustomerID,
         Discount
    FROM CTE
    WHERE Row_num = 1