sqlsql-servernorthwind

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


I need the MIN(Orderdate) and MAX(Orderdate) with the MAX(Orderdate) Freight values.

I've tried using a CTE and I am struggling to eliminate duplicate rows for the 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)

I am trying to get these results which should display 89 records.

  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 |


Solution

  • Just use conditional aggregation:

    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;
    

    Note that you do not appear to need the Customer table. All the information you need is in Orders (I doubt you are using Customer to remove rows.)