选择具有MAX(日期)运费值的MIN(日期)和MAX(日期)

时间:2019-04-09 20:02:03

标签: sql sql-server northwind

我需要MIN(Orderdate)和MAX(Orderdate)以及MAX(Orderdate)Freight值。

我曾经尝试过使用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 |

2 个答案:

答案 0 :(得分:2)

只需保持简单并符合问题即可。子查询CTE已经具有customerID和LastOrder(最大订购日期)。将CTE中的LastOrder列与Order表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 

答案 1 :(得分:0)

只需使用条件聚合:

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表。您需要的所有信息都在Orders中(我怀疑您正在使用Customer删除行。)