ORACLE SQL - 基于逻辑对记录进行分类

时间:2013-02-16 03:29:57

标签: sql oracle

基于逻辑对记录进行分类的最佳方法是什么?

例如,从此表中:

ID House  Farm
1  (null) (null)

我想输出:

ID Missing
1  House
1  Farm

除了下面明显的UNION之外,还有更好的方法吗?也许是一个什么时候?在处理更多条件时,UNION ALL不会轻易灵活。

select ID, 'House' as Missing from table where house is null
union all 
select ID, 'Farm' as Missing from table where farm is null

2 个答案:

答案 0 :(得分:3)

虽然我不知道它是否比UNION ALL更有效,但另一种选择是使用UNPIVOT,具体取决于您使用的Oracle版本:

SELECT ID, Missing
FROM (
    SELECT *
    FROM   YourTable
    UNPIVOT INCLUDE NULLS (IsMissing FOR Missing IN (House as 'House', Farm as 'Farm'))
  ) t
WHERE IsMissing IS NULL

这是SQL Fiddle

答案 1 :(得分:1)

请使用UNPIVOT检查结果。查看链接pivot and unpivot queries in 11gPIVOT and UNPIVOT Operators in Oracle Database 11g Release 1了解详情。

SELECT 
  ID, MISSING
FROM  
(
    SELECT  ID, NVL(HOUSE, 1) HOUSE, NVL(FARM, 1) FARM FROM YourTable
 )x
UNPIVOT (
 DCol
 FOR MISSING
 IN  (HOUSE, FARM) 
);

SELECT 
  ID, MISSING
FROM YourTable 
UNPIVOT INCLUDE NULLS (
DCol
FOR MISSING
IN  (HOUSE, FARM) 
);