SQL 如何在select语句中编写if条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5709777/
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
how to write a if condition within a select statement?
提问by userstackoverflow
I have a column which needs to be populated with ture/false/(N/A) data. This column is part of a select statement So, How can i achieve this?
我有一列需要填充 ture/false/(N/A) 数据。此列是 select 语句的一部分 那么,我该如何实现呢?
SELECT distinct
program_id,
prog_name,
Eitc_Active_Switch as Prog_Status,
progmap.client_id,
progmap.ORG_ID,
sec.calwinexists_ind as interface,
sec.Client_name
FROM ref_programs prog (nolock)
LEFT OUTER JOIN ref_county_program_map progmap (nolock)
ON progmap.program_id=prog.prog_id AND progmap.CLIENT_ID=prog.CLIENT_ID
INNER join sec_clients sec (nolock)
on sec.client_id=progmap.Client_id
'sec.calwinexists_ind as interface' is the column. the true/false should be displayed for only three records (AMC, AMBD, ACMNI) and 'N/A' for the rest of the records
'sec.calwinexists_ind as interface' 是列。仅应为三个记录(AMC、AMBD、ACMNI)显示真/假,其余记录应显示“N/A”
Can anyone help me?
谁能帮我?
回答by Cristian Boariu
You should use CASEexpression.
您应该使用CASE表达式。
Example:
例子:
SELECT name,salary,
CASE
WHEN salary <= 2000 THEN 'low'
WHEN salary > 2000 AND salary <= 3000 THEN 'average'
WHEN salary > 3000 THEN 'high'
END AS salary_level
FROM employees
ORDER BY salary ASC
And in this way you should adapt your query to match your needs.
通过这种方式,您应该调整您的查询以满足您的需求。
回答by bruno.zambiazi
Could you use a CASE WHEN control. Take a look at: http://dev.mysql.com/doc/refman/4.1/pt/control-flow-functions.html
您可以使用 CASE WHEN 控件吗?看看:http: //dev.mysql.com/doc/refman/4.1/pt/control-flow-functions.html