2012-04-11 93 views
1

表A更新一列組SQL服務器通過

int class del 
null 13 
null 13 
null 13 
12 13 
null 23 
null 23 
null 87 
null 74 
null 74 
null 65 
32 65 

所以,我想填充德爾= 'A',其中一個給定的類,它的所有int是否則返回null應該填充B.

預期結果:

表A

int class del 
null 13 B 
null 13 B 
null 13 B 
12 13 B 
null 23 A 
null 23 A 
null 87 A 
null 74 A 
null 74 A 
null 65 B 
32 65 B 

回答

2
update 
    TableA 
set 
    del = Case 
      when mcolint is null Then 'A' 
      Else 'B' 
    End 
from 
    TableA T 
inner join 
    (
     select 
      class, 
      MAX(colint) mcolint 
     from 
      TableA 
     group by 
      class 
    ) T1 
on 
    T.class = T1.class 
2

在SQL Server 2005 +,你可以做這樣的事情:

WITH calcDelValue AS (
    SELECT 
    *, 
    CASE 
     WHEN MAX(int) OVER (PARTITION BY class) IS NULL THEN 'A' 
     ELSE 'B' 
    END AS Value 
    FROM TableA 
) 
UPDATE calcDelValue 
SET del = Value 

OVER Clause (Transact-SQL)更多地瞭解開窗聚合函數WITH common_table_expression (Transact-SQL)以獲取有關的CTE(公共表表達式)