10

我有下表:

TestTable  
  ColumnA  
  Column1  
  Column2  
  Column3  
  Column4 

我想编写一个简单的 SQL 语句来检查 ColumnA 并根据它是否为空返回某些列。

像(伪)这样的东西:

If ColumnA Is Null
  SELECT ColumnA, Column1, Column2 
  FROM TestTable
Else
  SELECT ColumnA, Column3, Column4
  FROM TestTable

有任何想法吗?

4

3 回答 3

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 表达式 (Oracle)

于 2012-04-18T17:24:08.637 回答
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
于 2012-04-18T17:25:34.653 回答
3

给这只特殊猫剥皮的另一种方法:

SELECT ColumnA,
       NVL2(ColumnA, Column3, Column1),
       NVL2(ColumnA, Column4, Column2)
  FROM TestTable

分享和享受。

于 2012-04-18T17:39:24.823 回答