SQL 合并两个布尔值并将其转换为字符串列

SQL merge and convert two bools to string column

我有一个带有两个 smallint (bool) 列的 table。我想将这两列合并为 1 varchar (string) 列,然后删除这两个 smallint 列。它应该合并以便:

false false = "blue"
false true = "yellow"
true false = "red"

例如:

column_1    Column_2    Column_3
0           1           "yellow"
1           0           "red"
0           0           "blue"
0           0           "blue"

但是我真的不知道从哪里开始。 我正在使用 Microsoft SQL Server 2012

第一步是使用 ALTER TABLE. So you'll need to alter your table and add a new column with the VARCHAR format. Then you create the data with the following CASE WHEN:

创建新列
UPDATE TableNameHere
SET column_3 = CASE
    WHEN column_1 = 0 AND column_2 = 1 THEN "yellow"
    WHEN column_1 = 1 AND column_2 = 0 THEN "red"
    WHEN column_1 = 0 AND column_2 = 0 THEN "blue"
    --You can add an ELSE if the column should not be null
  END;

之后,您可以用另一个 ALTER TABLE 删除前两列。

请注意,我在 MySQL 文档中插入了文档,但这是标准的 SQL 语法,在 SQL 服务器上应该是相同的。

使用 case 语句。我为任何其他情况留下了 ELSE

select column1, column2,
       case 
           when column1 = 1 and column2 = 0 then 'red'
           when column1 = 0 and column2 = 1 then 'yellow'
           when column1 = 0 and column2 = 0 then 'blue'
           else 'Other'
      end as col3
from MyTable