SQL查询,根据两列中的值更改一列中的值

时间:2015-08-20 17:17:09

标签: sql sql-server sql-server-2012

如何根据两列中的值更改一列中的值。

select Name, acc_type , NewOld
from Account
Where account_type = 'footballer'
AND NewOld = 0  OR  NewOld = 1 

如果acc_type= footballerNewOld = 1acc_Type现在变为Retired

并且

如果acc_type= footballerNewOld = 0acc_Type现在变为New

编辑1:

我可以这样做吗;

UPDATE Account
SET acc_type = Retired
WHERE acc_type = footballer
AND NewOLD = 1

编辑2:

我试过

UPDATE dbo.Account
SET new_AccountType = CASE 
                 WHEN newOld = 1 THEN 'Retired'
                 WHEN newOld = 0 THEN 'New'
              END 
Where new_AccountType = 'Footballer' 
AND newOld IN (0,1) 

刚刚将new_AccountTypeIdName ='足球运动员'的所有内容更改为“已退役”,如果newOld为1或0则无关紧要?

为什么会这样?

2 个答案:

答案 0 :(得分:1)

使用Case声明

select Name, 
       case when NewOld = 1 then 'Retired' else 'New' End as acc_type, 
       NewOld
from Account
Where account_type = 'footballer'
AND NewOld in (0 , 1 )

此外,您的where子句将被解释为

(account_type = 'footballer' AND NewOld = 0)  OR  NewOld = 1 

但我想你需要这个

account_type = 'footballer' AND (NewOld = 0  OR  NewOld = 1).

您可以使用OR opertaor

而不是多个IN条件

答案 1 :(得分:0)

SQL Server 2005及更高版本

select Name 
     , NewOld
     ,CASE 
          WHEN NewOld = 1 THEN 'Retired'
          WHEN NewOld = 0 THEN 'New'
      END  AS acc_type 
from Account
Where account_type = 'footballer'
AND NewOld IN (0,1) 

SQL Server 2012及更高版本

select Name 
     , NewOld
     ,IIF(NewOld = 1 , 'Retired','New') AS acc_type 
from Account
Where account_type = 'footballer'
AND NewOld IN (0,1) 

FOR UPDATE 2005及以后

UPDATE Account
  SET acc_type  = CASE 
                     WHEN NewOld = 1 THEN 'Retired'
                     WHEN NewOld = 0 THEN 'New'
                  END 
Where account_type = 'footballer'
AND NewOld IN (0,1) 

FOR UPDATE 2012及以后

UPDATE Account
  SET acc_type  =  IIF(NewOld = 1 , 'Retired','New')
Where account_type = 'footballer'
AND NewOld IN (0,1)