当表值为0时,如何选择最接近的上述值是否为0?

时间:2016-03-31 20:55:49

标签: sql sql-server-2008 loops

在SQL 2008中,我正在寻找一种方法将所有0转换为最接近的值,而不是0.基本上,我想要这样:

+--------+-------+
| Number | Cost  |
+--------+-------+
|      1 | 5.84  |
|      2 | 0.00  |
|      3 | 0.00  |
|      4 | 0.00  |
|      5 | 0.00  |
|      6 | 5.98  |
|      7 | 0.00  |
|      8 | 0.00  |
+--------+-------+

看起来像这样:

+--------+-------+
| Number | Cost  |
+--------+-------+
|      1 | 5.84  |
|      2 | 5.84  |
|      3 | 5.84  |
|      4 | 5.84  |
|      5 | 5.84  |
|      6 | 5.98  |
|      7 | 5.98  |
|      8 | 5.98  |
+--------+-------+

问题是,循环是超级税收,因为我必须在数千个值上执行此操作。这是我尝试过的循环:

    WHILE (SELECT COUNT(*) FROM #table  WHERE cost is null) > 0

    BEGIN

        UPDATE TOP (1) #table
        SET cost = ((select cost from #table t2 where (f2.number = #table.number + 1)))
        WHERE cost = 0

    END

任何想法的人?

3 个答案:

答案 0 :(得分:1)

CREATE TABLE #numbers (number INT, cost DECIMAL(10, 3))

INSERT INTO #numbers
        (number, cost)
VALUES  
(      1 , 5.84  ),
(      2 , 0.00  ),
(      3 , 0.00  ),
(      4 , 0.00  ),
(      5 , 0.00  ),
(      6 , 5.98  ),
(      7 , 0.00  ),
(      8 , 0.00  )



UPDATE #numbers 
SET cost = (SELECT TOP 1 m.cost FROM #numbers m  WHERE cost > 0 AND n.number > m.number
    ORDER BY m.number desc
)
FROM #numbers n
WHERE cost = 0

SELECT * FROM #numbers


DROP TABLE #numbers

答案 1 :(得分:1)

update #table set cost = (
    select top 1 cost
    from #table t2
    where t2.number < #table.number
    and t2.cost <> 0
    order by number desc
)
where cost = 0

答案 2 :(得分:0)

假设您的表名是table1,请尝试以下查询:

update table1 set Cost = 
    case when Cost <> 0 then Cost
    else (select top 1 Cost from table1 t2 
      where t2.Cost <> 0 and t2.Number < table1.Number 
      order by table1.Number desc)
    end
from table1