1

我编写了一个存储过程,它为我提供了数据分析所需的原始数据。

该 SP 会立即使用以下结构填充一个临时表:

CREATE TABLE #Analysis
(
    AgreementID int,
    DueDate datetime,
    DateFrom datetime,
    DateTo datetime,
    AmountDue decimal(9,2),
    AmountPaid decimal(9,2),
    DueTD decimal(9,2),
    PaidTD decimal (9,2),
    ArrearsScore int
)

AgreementID 可以在该表中向上重复 6 条记录。

我需要做的是,对于每个协议 ID,我需要获取最后 6 行

这将允许我进行其余的分析。

我努力了:

    SELECT
          AN.*
    FROM
          #Analysis AS A
    LEFT OUTER JOIN
         (SELECT 
             TOP(6) * 
          FROM 
              #Analysis 
          ORDER BY 
              AgreementID, DueDate DESC
         ) AS AN ON A.AgreementID = AN.AgreementID
    WHERE AN.AgreementID IS NOT NULL

但这并没有给我想要的结果。

任何人都可以建议吗?

谢谢你。

4

1 回答 1

2

如果您正在使用SQL Server 2005+,则可以使用Common Table ExpressionWindowing function。为记录的值为 1ROW_NUMBER()的每个记录提供一个排名或值,AgreementID该值从 latest 排序DueDate

WITH records
AS
(
    SELECT  AgreementID,
            DueDate,
            DateFrom,
            DateToe,
            AmountDue,
            AmountPaid,
            DueTD,
            PaidTD,
            ArrearsScore,
            ROW_NUMBER() OVER(PARTITION BY AgreementID 
                        ORDER BY AgreementID, DueDate DESC) rn
    FROM    #Analysis
)
SELECT  AgreementID,
        DueDate,
        DateFrom,
        DateToe,
        AmountDue,
        AmountPaid,
        DueTD,
        PaidTD,
        ArrearsScore
FROM    records
WHERE   rn <= 6

不使用CTE

SELECT  AgreementID,
        DueDate,
        DateFrom,
        DateToe,
        AmountDue,
        AmountPaid,
        DueTD,
        PaidTD,
        ArrearsScore
FROM    
        (
            SELECT  AgreementID,
                    DueDate,
                    DateFrom,
                    DateToe,
                    AmountDue,
                    AmountPaid,
                    DueTD,
                    PaidTD,
                    ArrearsScore,
                    ROW_NUMBER() OVER(PARTITION BY AgreementID 
                                ORDER BY AgreementID, DueDate DESC) rn
            FROM    #Analysis
        ) records
WHERE   rn <= 6
于 2013-04-16T15:15:58.157 回答