2016-11-11 35 views
0

假设我有一个包含两个数字列的表:NUM和DEN。 我需要提取比率NUM/DEN仅当DEN不为0:否则比率应为0SQL查询中的公式中的IF语句

像这样:

select ID, [...] AS RATIO 
from Table 

其中[...]是某种相当于excel公式IF(DEN = 0; 0; NUM/DEN)。

有没有办法执行这种查询?

非常感谢!

+0

的可能的复制[如何执行IF ... THEN在SQL SELECT?] (http://stackoverflow.com/questions/63447/how-to-perform-an-if-then-in-an-sql-select) – uTeisT

+0

'SELECT ISNULL(NUM/NULLIF(DEN,0),0)'为Sql服务器 – Fabio

+0

如果你真的先用google搜索,你会花更少的时间。* downvoted&标记* – uTeisT

回答

1

这应该工作:

case 
    when DEN = 0 then 0 
    else NUM/DEN 
end 
0

如果SQL Server 2012中您可以使用:IIF

IIF (boolean_expression, true_value, false_value) 
0

是的,你正在寻找的是case。它有两个版本:

case [variable] 
    when [value1] then [output1] 
    when [value2] then [output2] 
    when [value3] then [output3] 
    ... 
    else [outputdefault] end 

case when [Boolean(True/false) expression 1] then [output1] 
     when [Boolean(True/false) expression 2] then [output2] 
     when [Boolean(True/false) expression 3] then [output3] 
    ... 
    else [outputdefault] end 
0

如果您正在使用SQL Server,你可以使用case语句像w0lf提到或者你可以使用iif语句,像这样:

select iif(age > 21, 'Allowed', 'Not Allowed') as status 
from test; 

例如:

create table test (
    fullname varchar (20), 
    age int 
); 

insert into test values 
('John', 10), 
('Matt', 90), 
('Jane', 25), 
('Ruby', 80), 
('Randy', null); 

结果

| fullname |  status | 
|----------|-------------| 
|  John | Not Allowed | 
|  Matt |  Allowed | 
|  Jane |  Allowed | 
|  Ruby |  Allowed | 
| Randy | Not Allowed | 

同样的事情可以写成

select case when age > 21 then 'Allowed' else 'Not Allowed' end as status 
from test; 

case声明被许多的数据库引擎。

如果你正在处理NULL和NOT NULL值,你也可以使用​​3210像这样:

select fullname, coalesce(age, 999) as status 
from test; 

结果将是:

| fullname | status | 
|----------|--------| 
|  John |  10 | 
|  Matt |  90 | 
|  Jane |  25 | 
|  Ruby |  80 | 
| Randy | 999 | 

起初你可能会认为​​3210做if age is null then 999 else age。它这样做,排序,但特别是​​3210输出列表中的第一个非空值。所以,coalesce(null, null, 45)将导致45 coalesce(null, 33, 45)将导致33

随意玩弄SQL小提琴:http://sqlfiddle.com/#!6/a41a7/6