使用 MAX(日期)运费值选择 MIN(日期)和 MAX(日期)

Selecting the MIN(date) and the MAX(date) with the MAX(date) Freight Values

我需要 MIN(订单日期)和 MAX(订单日期)以及 MAX(订单日期)运费值。

我已经尝试使用 CTE,但我正在努力消除 CustomerID 的重复行

USE Northwind
GO

WITH CTE AS (
SELECT a.customerID,
    MAX(b.OrderDate) AS LastOrder,
    MIN(b.OrderDate) AS FirstOrder

    FROM Orders AS b
INNER JOIN Customers AS a 
ON b.CustomerID = a.CustomerID
GROUP BY a.CustomerID
)

SELECT CTE.customerID, CTE.FirstOrder, d.OrderDate as LastOrder, d.Freight
FROM CTE 
INNER JOIN Orders as d
On CTE.CustomerID = d.CustomerID 
GROUP BY CTE.CustomerID, CTE.FirstOrder, d.Freight, d.OrderDate
HAVING d.OrderDate = MAX(d.OrderDate)

我正在尝试获取应显示 89 条记录的这些结果。

  CustomerID   FirstOrder   LastOrder    Freight
|  ALFKI     | 1997-08-25 | 1998-04-09 |  1.21   |
|  ANATR     | 1996-09-18 | 1998-03-04 |  39.92  |
|  ANTON     | 1996-11-27 | 1998-01-28 |  58.43  |
|  AROUT     | 1996-11-15 | 1998-04-10 |  33.80  |
|  BERGS     | 1996-08-12 | 1998-03-04 |  151.52 |

只使用条件聚合:

SELECT o.customerID,
      MAX(o.OrderDate) AS LastOrder,
      MIN(o.OrderDate) AS FirstOrder,
      MAX(CASE WHEN seqnum = 1 THEN o.freight END) as lastFreight
FROM (SELECT o.*,
             ROW_NUMBER() OVER (PARTITION BY o.customerID ORDER BY o.OrderDate DESC) as seqnum
      FROM Orders o
     ) o
GROUP BY o.CustomerID;

请注意,您似乎不需要 Customer table。您需要的所有信息都在 Orders 中(我怀疑您正在使用 Customer 删除行。)

只是为了保持简单并符合问题。子查询 CTE 已经有 customerID 和 LastOrder(Max Order Date)。将 CTE 中的 LastOrder 列连接到订单表 OrderDate 将给出预期的结果。

and d.OrderDate = CTE.LastOrder 

完整查询:

WITH CTE AS (
SELECT a.customerID,
    MAX(b.OrderDate) AS LastOrder,
    MIN(b.OrderDate) AS FirstOrder

    FROM Orders AS b
INNER JOIN Customers AS a 
ON b.CustomerID = a.CustomerID
GROUP BY a.CustomerID
)
SELECT CTE.customerID, CTE.FirstOrder, d.OrderDate as LastOrder, d.Freight
FROM CTE 
INNER JOIN Orders as d
On CTE.CustomerID = d.CustomerID 
and d.OrderDate = CTE.LastOrder