我有一个 select 语句,它将返回 2 列。
ID | IDParent
然后在我的程序中我必须测试if IDParent is < 1 then use ID ELSE use IDParent
有没有办法在 SQL 中使用类似 If Else 的条件来仅返回单个值?
我有一个 select 语句,它将返回 2 列。
ID | IDParent
然后在我的程序中我必须测试if IDParent is < 1 then use ID ELSE use IDParent
有没有办法在 SQL 中使用类似 If Else 的条件来仅返回单个值?
您可以使用CASE
SELECT ...,
CASE WHEN IDParent < 1 THEN ID ELSE IDPArent END AS ColumnName,
...
FROM tableName
在这里,使用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
SELECT CASE WHEN IDParent < 1
THEN ID
ELSE IDParent
END AS colname
FROM yourtable
查询将如下所示
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]
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
您可以在查询下使用简单if
的语句,select
如下所述
if(some_condition,if_satisfied,not_satisfied)
SELECT IF(IDParent < 1,ID,IDParent) FROM yourTable ;
这是一些使用示例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;
希望这可以帮助
SELECT IF(COLUMN_NAME = "VALUE", "VALUE_1", "VALUE_2") AS COLUMN_NAME
FROM TABLE_NAME;
或者
SELECT (CASE WHEN COLUMN_NAME = "VALUE" THEN 'VALUE_1' ELSE 'VALUE_2' END) AS COLUMN_NAME
FROM TABLE_NAME;
您还可以使用联合构造。我不确定 CASE 是否是一个常见的 SQL 构造......
SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION
SELECT IDParent FROM tabName WHERE IDParent>1
select
CASE WHEN IDParent is < 1 then ID else IDParent END as colname
from yourtable
我对此结果有疑问:
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