选择语句中的 SQL 条件列数据返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9290994/
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
SQL Conditional column data return in a select statement
提问by JL.
Here is a simplication of the problem: I have a select that looks like this:
这是问题的简化:我有一个看起来像这样的选择:
Select ID, Assignee, WorkStream from assignees;
And a snap shot of the data returned looked like this
返回的数据快照如下所示
1|Joe Soap|Internal
2|Mrs Balls|External
What I would like to do is have the select not display the Assignee name if the worksteam is internal. Instead to display the Workstream.
如果工作组是内部的,我想做的是选择不显示受让人名称。而是显示工作流。
So for example the outcome I want to achieve would be this:
例如,我想要实现的结果是:
1|Internal|Internal
2|Mrs Balls|External
I hope this makes sense? Basically a conditional select that can detect if a certain column contains a certain value, then replace another columns value with [whatever].
我希望这是有道理的?基本上是一个条件选择,可以检测某个列是否包含某个值,然后用 [whatever] 替换另一个列的值。
Thanks in advance!
提前致谢!
EDIT I want to achieve something like this:
编辑我想实现这样的目标:
Select ID, if (workstream='internal' select Workstream as Assignee - else - select Assignee as Assigneee), WorkStream from assignees;
回答by Lieven Keersmaekers
You didn't mention your DBMS but a searched CASE
statement works in all major DBMS's I know off.
您没有提到您的 DBMS,但搜索CASE
语句适用于我所知道的所有主要 DBMS。
SELECT ID
, CASE WHEN WorkStream = 'Internal'
THEN WorkStream
ELSE Assignee
END AS Assignee
, Workstream
FROM assignees
Reference: MSDN
参考:MSDN
CASE
Evaluates a list of conditions and returns one of multiple possible result expressions.
案件
评估条件列表并返回多个可能的结果表达式之一。
回答by Pongsathon.keng
SELECT ID,
CASE WorkStream WHEN 'Internal' THEN 'INTERNAL' ELSE Assignee as Assignee, WorkStream from assignees
I hope this help.
我希望这会有所帮助。