SQL查询中公式内的IF语句

时间:2016-11-11 14:05:55

标签: sql if-statement

我们说我有一个包含两个数字列的表:NUM和DEN。 我只需要在DEN不为0时提取比率NUM / DEN:否则该比率应为0.

这样的事情:

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

其中[...]是excel公式IF的某种等价物(DEN = 0; 0; NUM / DEN)。

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

非常感谢!

4 个答案:

答案 0 :(得分:1)

这应该有效:

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

答案 1 :(得分:0)

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

IIF ( boolean_expression, true_value, false_value ) 

答案 2 :(得分: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

答案 3 :(得分:0)

如果您使用的是SQL Server,可以使用{0}提到的case语句,或者可以使用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值而非null值,您也可以使用coalesce,如下所示:

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

结果将是:

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

首先,您可能会认为coalesce执行if age is null then 999 else age。它就是这样,排序,但特别是coalesce输出列表中的第一个非空值。因此,coalesce(null, null, 45)将导致45。coalesce(null, 33, 45)将导致33。

随意使用SQL Fiddle:http://sqlfiddle.com/#!6/a41a7/6