在SQL Select语句中使用If else

问题描述 投票:37回答:10

我有一个select语句,它将返回2列。

ID | IDParent

然后在我的程序中,我必须测试if IDParent is < 1 then use ID ELSE use IDParent

有没有办法在SQL中使用If Else like条件只返回单个值?

sql sql-server
10个回答
80
投票

你可以使用CASE

SELECT   ...,
         CASE WHEN IDParent < 1 THEN ID ELSE IDPArent END AS ColumnName,
         ...
FROM     tableName

0
投票

您可以在if查询下使用简单的select语句,就像我在下面描述的那样

if(some_condition,if_satisfied,not_satisfied)

SELECT IF(IDParent < 1,ID,IDParent)  FROM yourTable ;

20
投票
SELECT CASE WHEN IDParent < 1 
            THEN ID 
            ELSE IDParent 
       END AS colname 
FROM yourtable

19
投票

在这里,使用CASE Statement并找到结果:

select (case when condition1 then result1
             when condition2 then result2
             else result3
             end) as columnname from tablenmae:

例如:

select (CASE WHEN IDParent< 1 then ID 
             else IDParent END) as columnname
from tablenmae

4
投票

查询将如下所示

SELECT (CASE WHEN tuLieuSo is null or tuLieuSo=''
            THEN 'Chưa có đĩa' 
            ELSE 'Có đĩa' End) AS tuLieuSo,moTa
FROM [gPlan_datav3_SQHKTHN].[dbo].[gPlan_HoSo]

1
投票

sql server 2012

  with
  student as 
(select sid,year from (
values (101,5),(102,5),(103,4),(104,3),(105,2),(106,1),(107,4)
) as student(sid,year)
)
select iif(year=5,sid,year) as myCol,* from student


 myCol  sid year
101 101 5
102 102 5
4   103 4
3   104 3
2   105 2
1   106 1
4   107 4

0
投票

您还可以使用union构造。我不确定CASE是否是一个常见的SQL构造......

SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION 
SELECT IDParent FROM tabName WHERE IDParent>1

0
投票
select 
CASE WHEN IDParent is < 1 then ID else IDParent END as colname 
from yourtable

0
投票

我有一个查询结果:

SELECT Top 3
 id,
 Paytype
 FROM dbo.OrderExpresses
 WHERE CreateDate > '2018-04-08'

结果是:

22082   1
22083   2
22084   1

我想在查询中更改代码字符串,所以我使用此代码:

SELECT TOP 3
 id,
 CASE WHEN Paytype = 1 THEN N'Credit' ELSE N'Cash' END AS PayTypeString
 FROM dbo.OrderExpresses
 WHERE CreateDate > '2018-04-08'

结果是:)

22082   Credit
22083   Cash
22084   Credit

0
投票

以下是使用CASE WHEN的一些示例

SELECT 
    CASE WHEN A > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            A
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 and B > 1 THEN
            'Greater than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE
            'less than 1'
    END  
FROM TRIANGLES

.

SELECT 
    CASE WHEN A > 1 THEN
            'greater than 1'
         ELSE CASE WHEN A >= 0 THEN
                      'greater than or equal 0'
                   ELSE
                      'less than 0'
              END        
    END  
FROM TRIANGLES;

跳吧帮忙