I am creating new columns but in particular I want to say if a value of a column is equal to a value, then change a corresponding column. For example:
我正在创建新列,但特别是我想说如果列的值等于某个值,则更改相应的列。例如:
SELECT
Col1 as c1
,Col2 as c2
,CASE CAST([COB] as varchar(50))
WHEN 'Engineering' then set c1 = 1
ELSE 0
END AS [Class of Business]
FROM
....
but I can't get it to work, for instance if a entry in the column [COB] was 'engineering' then I want it to set (on the same row) the column c1 to 0, else just fill the column c1 with 0's
但我不能让它工作,例如,如果[COB]列中的条目是'工程',那么我希望它将列c1设置(在同一行上)为0,否则只需填写列c1 0的
4 个解决方案
#1
1
If you only want to query your table, you can return 1 or 0 in base of COB status without reassign to c1
the new value.
如果您只想查询表,则可以在COB状态的基础上返回1或0,而无需将新值重新分配给c1。
Try this:
尝试这个:
SELECT
CASE
WHEN CAST([COB] as varchar(50)) = 'Engineering' then 1
ELSE Col1
END AS c1,
Col2 as c2
FROM ...
#2
1
So when COB = Engineering you want c1 to be 1 otherwise just the current value of C1. If that is the cae then......
因此,当COB =工程时,您希望c1为1,否则只是C1的当前值。如果那是cae那么......
SELECT
CASE CAST([COB] as varchar(50))
WHEN 'Engineering' then 1
ELSE c1
END AS c1
,Col2 as c2
FROM
..
#3
1
That's not the way SELECT
works. You're looking for something like this:
那不是SELECT的工作方式。你正在寻找这样的东西:
SELECT
--Col1 as c1
CASE CAST([COB] as varchar(50))
WHEN 'Engineering' then 1
ELSE 0
END AS c1
,Col2 as c2
,COB as [Class of Business]
FROM
#4
0
Why are you doing the cast()
?
你为什么要做演员()?
SELECT Col1 as c1,
Col2 as c2,
(CASE WHEN [COB] = 'Engineering' THEN 1 ELSE 0 END) as [Class of Business]
FROM . . .;
You can use a searched CASE
for this purpose. But with one comparison, I think the above is easier to read.
您可以使用搜索的CASE来实现此目的。但通过一次比较,我认为上述内容更容易阅读。
#1
1
If you only want to query your table, you can return 1 or 0 in base of COB status without reassign to c1
the new value.
如果您只想查询表,则可以在COB状态的基础上返回1或0,而无需将新值重新分配给c1。
Try this:
尝试这个:
SELECT
CASE
WHEN CAST([COB] as varchar(50)) = 'Engineering' then 1
ELSE Col1
END AS c1,
Col2 as c2
FROM ...
#2
1
So when COB = Engineering you want c1 to be 1 otherwise just the current value of C1. If that is the cae then......
因此,当COB =工程时,您希望c1为1,否则只是C1的当前值。如果那是cae那么......
SELECT
CASE CAST([COB] as varchar(50))
WHEN 'Engineering' then 1
ELSE c1
END AS c1
,Col2 as c2
FROM
..
#3
1
That's not the way SELECT
works. You're looking for something like this:
那不是SELECT的工作方式。你正在寻找这样的东西:
SELECT
--Col1 as c1
CASE CAST([COB] as varchar(50))
WHEN 'Engineering' then 1
ELSE 0
END AS c1
,Col2 as c2
,COB as [Class of Business]
FROM
#4
0
Why are you doing the cast()
?
你为什么要做演员()?
SELECT Col1 as c1,
Col2 as c2,
(CASE WHEN [COB] = 'Engineering' THEN 1 ELSE 0 END) as [Class of Business]
FROM . . .;
You can use a searched CASE
for this purpose. But with one comparison, I think the above is easier to read.
您可以使用搜索的CASE来实现此目的。但通过一次比较,我认为上述内容更容易阅读。