我有下表:
TestTable
ColumnA
Column1
Column2
Column3
Column4
我想编写一个简单的SQL语句来检查ColumnA,并根据它是否为null返回某些列。
像(伪)的东西:
If ColumnA Is Null
SELECT ColumnA, Column1, Column2
FROM TestTable
Else
SELECT ColumnA, Column3, Column4
FROM TestTable
有什么想法吗?
答案 0 :(得分:17)
使用SQL CASE表达式:
SELECT
ColumnA,
CASE WHEN ColumnA IS NULL THEN Column1 ELSE Column3 END AS ColumnB,
CASE WHEN ColumnA IS NULL THEN Column2 ELSE Column4 END AS ColumnC
FROM
TestTable
请参阅:
CASE (SQL-Server Transact-SQL)
CASE Expressions (Oracle)
答案 1 :(得分:3)
我能想到几条路线,没有一条路可能很漂亮......
人们经常会找到第一个,然后寻找更好的东西。我不确定那里有什么更好的。
SELECT
ColumnA,
CASE WHEN ColumnA IS NULL THEN Column1 ELSE Column2 END AS ColumnB,
CASE WHEN ColumnA IS NULL THEN Column3 ELSE Column4 END AS ColumnC
FROM
yourTable
或者...
SELECT
yourTable.ColumnA,
subTable.ColumnB,
subTable.ColumnC
FROM
yourTable
CROSS APPLY
(
SELECT yourTable.Column1 AS ColumnB, yourTable.Column3 AS ColumnC WHERE yourTable.ColumnA IS NULL
UNION ALL
SELECT yourTable.Column2 AS ColumnB, yourTable.Column4 AS ColumnC WHERE yourTable.ColumnA IS NOT NULL
)
AS subTable
或者...
SELECT
ColumnA,
Column1 AS ColumnB,
Column2 AS ColumnC
FROM
yourTable
WHERE
ColumnA IS NULL
UNION ALL
SELECT
ColumnA,
Column2 AS ColumnB,
Column4 AS ColumnC
FROM
yourTable
WHERE
ColumnA IS NOT NULL
答案 2 :(得分:3)
另一种给这只特殊猫皮肤涂抹的方法:
SELECT ColumnA,
NVL2(ColumnA, Column3, Column1),
NVL2(ColumnA, Column4, Column2)
FROM TestTable
分享并享受。