2016-04-11 27 views
0

我有5列如表:賦值給基於其他列在SQL Server 2008中的列更有效的方式值

id value1 value2 value3 Score 
1 X  X  X  
2 X  Y  Z  
3 Y  Z  Z  
4 X  Z  X 

我想是分配等於Y和Z最終值(沒有X)像每列:

id value1 value2 value3 final 
1 X  X  X  0 
2 X  Y  Z  2 
3 Y  Z  Z  3 
4 X  Z  X  1 

我這樣做的方式是:

Update table 
set final = 3 
where value1 <> 'X' and value2 <> 'X' and value3 <> 'X' 

Update table 
set final = 2 
where (value1 <> 'X' and value2 <> 'X' and value3 = 'X') 
    OR (value1 = 'X' and value2 <> 'X' and value3 <> 'X') 
    OR (value1 <> 'X' and value2 = 'X' and value3 <> 'X') 

Update table 
set final = 1 
where (value1 <> 'X' and value2 = 'X' and value3 = 'X') 
    OR (value1 = 'X' and value2 <> 'X' and value3 = 'X') 
    OR (value1 = 'X' and value2 = 'X' and value3 <> 'X') 

Update table 
set final = 0 
where value1 = 'X' and value2 = 'X' and value3 = 'X' 

我想問一下我f有沒有比這更聰明/更有效的方法?任何意見,將不勝感激。謝謝!

+0

的應用情況... – Squirrel

回答

0

使用CASE WHEN。 。 。

Update table 
set final = CASE WHEN value1<>'X' and value2<>'X' and value3<>'X' THEN 3 
        WHEN (value1<>'X' and value2<>'X' and value3='X') 
        OR (value1='X' and value2<>'X' and value3<>'X') 
        OR (value1<>'X' and value2='X' and value3<>'X') THEN 2 
        WHEN (value1<>'X' and value2='X' and value3='X') 
        OR (value1='X' and value2<>'X' and value3='X') 
        OR (value1='X' and value2='X' and value3<>'X') THEN 1 
        WHEN value1='X' and value2='X' and value3='X' THEN 0 
        END 
2

這是你想要的嗎?

Update table 
    set final = ((case when value1 <> 'X' then 1 else 0 end) + 
        (case when value2 <> 'X' then 1 else 0 end) + 
        (case when value3 <> 'X' then 1 else 0 end) 
       ); 

這個數值不是X

這裏是另一種方法:

Update table 
     set final = len(replace(value1 + value2 + value3, 'X', ''); 

注:如果列確實有只有一個字符值這僅適用。

0

使用計算列。如果沒有獲得所需的輸出,請糾正我。

CREATE TABLE GRADES (
id INT 
,VALUE1 VARCHAR(10) 
,VALUE2 VARCHAR(10) 
,VALUE3 VARCHAR(10) 
,final INT AS (
    (
     CASE 
      WHEN value1 <> 'X' 
       THEN 1 
      ELSE 0 
      END 
     ) + (
     CASE 
      WHEN value2 <> 'X' 
       THEN 1 
      ELSE 0 
      END 
     ) + (
     CASE 
      WHEN value3 <> 'X' 
       THEN 1 
      ELSE 0 
      END 
     ) 
    ) 
); 
0
create TRIGGER test 
    ON [dbo].[YourTable] 
    AFTER INSERT 
AS 
BEGIN 
    declare @Id  int 
    declare @value1  nvarchar(10) 
    declare @value2  nvarchar(10) 
    declare @value3  nvarchar(10) 
    declare @Count int =0 

    select top(1) @Id=id, @value1=[m1] ,@value2=[m2],@value3=[m3] from [dbo].[Table_3] order by id DESC 
    if @value1='x' 
    begin 
    set @[email protected]+1 
    end 
    if @value2='x' 
    begin 
    set @[email protected]+1 
    end 
    if @value3='x' 
    begin 
    set @[email protected]+1 
    end 
    update [dbo].[Table_3] 
    set [email protected] 
    where id [email protected] 
END