1

我的问题是这样的

我有一个正在处理的查询,我有一些值为 0。我希望能够从上个月获取一个不为零的值并将其替换为零。请参见下面的示例。

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

在此处输入图像描述

所以我想取数字 2455 并将其输入到它显示为 0 的库存中,将上个月的余额数作为当前月份的库存水平。这甚至可能吗?

4

2 回答 2

1

您可以使用以下查询找到每个项目的前一个非零级别(对于零级别项目):

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

即使先前的非零水平是几个月前,这也将起作用。

于 2012-11-01T19:51:59.043 回答
0

沿着这些思路,这仅在上个月非零时才有效....

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
于 2012-11-01T19:43:37.293 回答