第二和第三个表格中值最高的行

时间:2016-07-18 12:11:23

标签: sql-server

我在SQL Server(客户,策略和声明)中有三个链接表,并且需要为每个显示其最新策略的客户以及该策略中的最新索引获取记录。客户的最高PolicyID是其最新的策略,而最高的ClaimID是最新的策略声明。

我有以下查询来显示所有政策/声明,但如何将其限制为最新/最高ID?

SELECT C.CustomerID, C.FirstName, C.LastName, P.PolicyID, P.PolicyDate, P.PolicyType, CL.ClaimID, CL.ClaimDate, CL.ClaimDescription
FROM Customers C INNER JOIN Policies P ON C.CustomerID = P.CustomerID
INNER JOIN Claims CL ON P.PolicyID = CL.PolicyID

1 个答案:

答案 0 :(得分:1)

试试这个,

;WITH CTE AS
(
    SELECT C.CustomerID, C.FirstName, C.LastName, P.PolicyID, P.PolicyDate, P.PolicyType, CL.ClaimID, CL.ClaimDate, CL.ClaimDescription
        ,ROW_NUMBER() OVER(PARTITION BY C.CustomerID ORDER BY P.PolicyID DESC) PolicyOrder
        ,ROW_NUMBER() OVER(PARTITION BY C.CustomerID, P.PolicyID ORDER BY CL.ClaimID DESC) ClaimOrder
    FROM Customers C INNER JOIN Policies P ON C.CustomerID = P.CustomerID
    INNER JOIN Claims CL ON P.PolicyID = CL.PolicyID
)
SELECT 
    *
FROM CTE c
WHERE c.PolicyOrder = 1
    AND c.ClaimOrder = 1