Question: My question is this, 

I have a query I'm working on and I have some values that are 0. I want to be able to take a value from a previous month that is not zero and put it in place of the zero. See the example below. 

```
SELECT item,
       stock,
       sold,
       level,
       month,
       year
FROM   agingdata
GROUP  BY item,
          stock,
          sold,
          month,
          year,
          level
HAVING ( item = @Item )
ORDER  BY year,
          month 

```

![enter image description here](https://i.stack.imgur.com/34WLI.png)

So I want take the number 2455 and input it into the stock where it says 0, taking last months balance number as the current months stock level. Is that even possible?

Answer: 
You can find the previous non-zero level per item (for zero level items) using this query:

```
SELECT find.item, find.month, find.year, result.level
FROM AgingData result 
JOIN (
  SELECT original.item, original.month, original.year, max(cast(cast(previous.year as varchar) + '-' + cast(previous.month as varchar) + '-1' as datetime)) previous_date
  FROM AgingData original
  JOIN AgingData previous
    ON original.item = previous.item
     AND ((original.year > previous.year)
         OR (original.year = previous.year AND original.month > previous.month))
  WHERE original.level = 0
    AND previous.level != 0
  GROUP BY original.item, original.month, original.year ) find
ON result.item = find.item
  AND cast(cast(result.year as varchar) + '-' + cast(result.month as varchar) + '-1' as datetime) = find.previous_date

```

This will work even if the previous non-zero level is several months before.
Something along these lines, this only works if the previous month is non-zero....

```
SELECT cur.Item, 
       CASE 
            WHEN (cur.Stock<>0) 
            THEN cur.Stock
            ELSE prev.Stock
       END as Stock, 
       cur.Sold, 
       cur.Level, 
       cur.Month, 
       cur.Year 
FROM AgingData cur 
LEFT OUTER JOIN AgingData prev 
     ON prev.item=cur.item and prev.Month = cur.Month - 1
GROUP BY cur.Item, cur.Stock, cur.Sold, cur.Month, cur.Year, cur.Level 
HAVING (cur.Item = @Item) 
ORDER BY cur.Year, cur.Month

```