从选择查询中获取最后六行

时间:2013-04-16 15:12:14

标签: sql sql-server stored-procedures

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

此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个记录之上。

我需要做的是,对于每个AgreementID,我需要获得最后的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

但这并没有给我预期的结果。

有人可以提供建议吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

如果您使用SQL Server 2005+,则可以使用Common Table ExpressionWindowing functionROW_NUMBER()为每个AgreementID提供排名或值,该记录的值为1,从最新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