2012-11-23 77 views
31

我有一個select語句,它將返回2列。在SQL Select語句中使用If If else

ID | IDParent 

然後在我的節目,我一定要考if IDParent is < 1 then use ID ELSE use IDParent

有沒有使用別的一個像如果條件SQL只返回一個值的方法嗎?

+0

[堆棧溢出鏈接]:http://stackoverflow.com/questions/5951157/mysql-if-in-select-statement希望這可以幫助 – macken88

回答

64

可以使用CASE

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

在這裏,用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 
0

你也可以使用一個工會構造UCT。我不知道的情況是常見的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 
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