我编写了一个存储过程,它为我提供了数据分析所需的原始数据。
此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
但这并没有给我预期的结果。
有人可以提供建议吗?
谢谢。
答案 0 :(得分:2)
如果您使用SQL Server 2005+
,则可以使用Common Table Expression
和Windowing function
。 ROW_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