获取差价日期的最高记录

时间:2018-08-16 17:48:52

标签: sql sql-server

我尝试仅获取每个客户的最后一个订单记录。自动取款机我有这个主意,但它给了我所有人订单日期。 我正在使用数据库AdventurerWorks2012

SELECT
        H.CustomerID                   AS Customer,
        H.SalesOrderID                 AS OrderNumber,
        MAX(CAST(H.OrderDate AS DATE)) AS DateOrder
FROM
        Sales.SalesOrderHeader H
    JOIN
        Sales.SalesOrderDetail D
            ON H.SalesOrderID = D.SalesOrderID
GROUP BY
        H.CustomerID,
        H.SalesOrderID
ORDER BY
        CustomerID;

3 个答案:

答案 0 :(得分:0)

您可以使用TOP 1 WITH TIES

select top 1 with ties
*
From 
Sales.SalesOrderHeader H 
INNER JOIN Sales.SalesOrderDetail D
ON H.SalesOrderID = D.SalesOrderID
ORDER BY row_number() over (partition by H.CustomerID order by H.OrderDate  desc)

这适用并以row_number()进行订购,为每个客户的订单提供一个ID,该ID从1开始,并根据OrderDate到N。 WITH TIES允许我们为每个客户返回TOP 1

另一种方法是使用CTE

;with cte as(
    select top 1 with ties
    *, RN =  row_number() over (partition by H.CustomerID order by H.OrderDate  desc)
    From 
    Sales.SalesOrderHeader H 
    INNER JOIN Sales.SalesOrderDetail D
    ON H.SalesOrderID = D.SalesOrderID)

select *
from cte
where RN = 1

答案 1 :(得分:0)

我认为您不需要执行JOIN

SELECT h.*
FROM Sales.SalesOrderHeader h
WHERE OrderDate = (SELECT MAX(h1.OrderDate) 
                   FROM Sales.SalesOrderHeader h1
                   WHERE h.CustomerID = h1.CustomerID 
                  );

通过这种方式,您将获得customer,其中包含最新的订单信息。

答案 2 :(得分:0)

select top 1 with ties
H.CustomerID AS Customer,
H.SalesOrderID as OrderNumber,
H.OrderDate As DataLast
From 
Sales.SalesOrderHeader H 
INNER JOIN Sales.SalesOrderDetail D
ON H.SalesOrderID = D.SalesOrderID
ORDER BY row_number() over (partition by H.CustomerID order by H.OrderDate  desc)

像我需要的这项工作。谢谢!