使用 CASE 在 SQL 中选择一个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4142486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using CASE to select a field in SQL?
提问by Poku
Based on if one field in the database is equal to something, I want to select the value of another field. I was thinking that I could use CASE THEN
but I can't get it to return the value of a field.
根据数据库中的一个字段是否等于某个字段,我想选择另一个字段的值。我在想我可以使用CASE THEN
但我无法让它返回字段的值。
Here is what I have tried so far:
这是我迄今为止尝试过的:
SELECT LastName, CASE FirstName WHEN 'Ian' THEN JobNo END FROM Employees
JobNo
is the name of the field which I want to get the value from.
JobNo
是我想从中获取值的字段的名称。
回答by mjallday
you're missing the else statement in your case statement, once that's in there it should work
你在你的 case 语句中缺少 else 语句,一旦它在那里它应该工作
like this:
像这样:
SELECT LastName,
CASE FirstName WHEN 'Ian' THEN JobNo ELSE -1 END
FROM Employees
回答by Preet Sangha
try this
尝试这个
SELECT LastName, CASE WHEN FirstName ='Ian' THEN JobNo else null END
FROM Employees
回答by AdaTheDev
You need to define the ELSE:
您需要定义 ELSE:
SELECT LastName, CASE FirstName WHEN 'Ian' THEN JobNo ELSE FirstName END
FROM Employees
I've defaulted to return the FirstName, if you don't want that just replace with something else. Just make sure the datatypes are equivalent to avoid potential issues (I've assumed JobNo is a varchar ref code for purpose of demonstrating syntax).
我默认返回名字,如果你不想要,只需用其他东西替换。只需确保数据类型等效以避免潜在问题(为了演示语法,我假设 JobNo 是 varchar 引用代码)。
回答by AdaTheDev
Adding an ELSE condition won't hurt, but you may also need a column name for your new column - like so:
添加 ELSE 条件不会有什么坏处,但您可能还需要新列的列名 - 如下所示:
SELECT LastName,
CASE FirstName
WHEN 'Ian' THEN JobNo
ELSE 0
END IansJobNo
FROM Employees
回答by Tebo
Here it is:
这里是:
SELECT LastName,
JobNo = CASE
WHEN FirstName = 'Ian' THEN JobNo END
FROM Employees
回答by ThE uSeFuL
The sql syntax seems correct to me. I tried it myself and works fine. May be you are missing something else. The following is a sample output I get,
sql 语法对我来说似乎是正确的。我自己试过了,效果很好。可能是你错过了别的东西。以下是我得到的示例输出,
回答by JIYAUL MUSTAPHA
CASE @Temp WHEN 1 THEN ISnull(tbl1.t1,0) WHEN 2 THEN ISnull(tbl1.t2,0) END AS Value
CASE @Temp WHEN 1 THEN ISnull(tbl1.t1,0) WHEN 2 THEN ISnull(tbl1.t2,0) END AS Value