我在使用哪种SQL逻辑时遇到问题,以便在临时表中找到政策编号(第2列),例如EAB1507017,在余额为0.00(第7列,最后一秒)。您会注意到列出的第二项策略EAB1507600已正确完成,但EAB1507017却未完成,我正在此临时表中查找那些在输入“代理退款”条目之前,运行余额为0的记录。
这是我的SQL代码:
SELECT glJournalID, PolicyNo, Description, IsReceipt, TransactionDate, TransactionAmount,
SUM(TransactionAmount) OVER (PARTITION BY PolicyNo ORDER BY glJournalID asc ROWS UNBOUNDED PRECEDING) as RunningBalance,
UserID
FROM #tmpTableResults
ORDER BY PolicyNo asc, glJournalID asc;
任何帮助/指导将不胜感激。谢谢。
答案 0 :(得分:1)
未经测试,但是我认为这将为您提供独特的PolicyNo
,在余额为'Agent Refund'
之后立即具有0.00
。关键是使用ROW_NUMBER()
,以便为每个PolicyNo
创建一个无间隙的序列,使您可以进行精确的前瞻或后瞻。
WITH T AS (
SELECT
PolicyNo,
SUM(TransactionAmount) OVER (
PARTITION BY PolicyNo
ORDER BY glJournalID asc
ROWS UNBOUNDED PRECEDING
) AS RunningBalance,
Description,
ROW_NUMBER() OVER(PARTITION BY PolicyNo ORDER BY glJournalID) AS RowNum
FROM #tmpTableResults
)
SELECT DISTINCT T.PolicyNo
FROM T
INNER JOIN T T2
ON
T2.PolicyNo = T.PolicyNo
AND T2.RowNum = T.RowNum + 1
AND T2.Description = 'Agent Refund'
WHERE T.RunningBalance = 0.00