Source Data :
Account Period Amount
AC100 January 100
AC100 February 0
AC100 March 0
AC100 April 0
AC100 May 0
AC100 June 600
AC100 July 700
AC100 August 0
AC100 September 0
AC100 October 1000
AC100 November 0
AC100 December 1200
I use this query
WITH CTE AS (
SELECT
Account,
Period,
Amount,
LAG(Amount, 1, 0) OVER (PARTITION BY Account ORDER BY (SELECT NULL)) AS PreviousAmount
FROM TableA
)
SELECT
Account,
Period,
CASE WHEN Amount = 0 THEN PreviousAmount ELSE Amount END AS Amount
FROM CTE
but the results only take the previous month which has an amount like the following picture:
How do I ensure that amount 0 remains filled with the previous number?
2条答案
按热度按时间r1zk6ea11#
This is a gaps and islands problem, You can solve it using window function
sum()
to calculate a running total, this creates islands where rows with consecutive months have the same rn value.The
max()
window function used to find the maximum amount within each island for each account.Results :
Demo here
9rygscc12#
Using your example data:
You can achieve this with an
OUTER APPLY
to find the last non-zeroamount
and return that instead when theamount
value is zero:Results: