我有一个表,其中包含2列,这些列存储可以达到的某些阈值。 该表的列为:ThresholdValue(INT),Reached(BIT),该表如下所示:
ThresholdValue | Reached
------------------------
10000 | 0
20000 | 0
30000 | 0
45000 | 0
50000 | 0
我需要根据已达到的阈值更新已达到的列。 例如,当达到的值是 25000 时,我希望将第二个行设置为1 ,因此看起来像这样
ThresholdValue | Reached
------------------------
10000 | 0
20000 | 1
30000 | 0
45000 | 0
50000 | 0
解决此问题的最简单方法是什么? 任何提示将不胜感激
答案 0 :(得分:2)
您可以使用子查询来标识该行:
update t
set reached = 1
from (select top (1) t.*
from t
where t.ThresholdValue <= 25000
order by ThresholdValue desc
) t;
另一种方法是查看 next 值:
update t
set reached = 1
from (select t.*, lead(ThresholdValue) over (order by ThresholdValue) as next_tv
from t
) t
where t.ThresholdValue <= 25000 and
(t.next_tv > 25000 or t.next_tv is null);