将数字从一列转换为另一列= 0

时间:2012-11-01 19:24:19

标签: sql

我的问题是这个,

我有一个我正在处理的查询,我有一些值为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 

enter image description here

所以我想把数字2455输入到它所说的0的股票中,将上个月的余额数作为当前的月份股票水平。这甚至可能吗?

2 个答案:

答案 0 :(得分: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

即使之前的非零水平是几个月之前,这也会有效。

答案 1 :(得分: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