将null替换为具有相同id的已知值

时间:2011-06-02 08:44:54

标签: tsql

我怎样才能以最佳方式做到这一点?

ID FLAG VALUE
----------------------------
1   Y   52
1   N   NULL
2   Y   51
3   N   54

输出

ID FLAG VALUE
----------------------------
1   Y   52
1   N   52
2   Y   51
3   N   54

2 个答案:

答案 0 :(得分:3)

UPDATE 
  theTable
SET 
  value = (SELECT MAX(value) FROM theTable i WHERE i.id = theTable.id)
WHERE
  value IS NULL

答案 1 :(得分:1)

你可以用两种方式做到这一点

SELECT Id,
       Flag, 
       MAX(Value) OVER(PARTITION BY Id) CValue
FROM   Table_1

select X.Id, X.Flag,
case when ISNULL(X.Value,0) = 0 then 
(select MAX(A.Value) from Table_1 A where A.Id = X.Id)
 else X.Value end
from Table_1 X