Oracle:检查元组中的NOT NULL

时间:2015-02-21 04:05:17

标签: sql oracle tuples notnull

目标:从Order表中选择记录,其中(delivery_date,type)不在(NULL,' A')。

select * from Orders; 

 Table : Orders

 No     Type  Delivery_Date
  1      A      null
  2      B      20150120
  3      A      20150115
  4      A      20150115
  5      A      20150111
  6      A      20150112
  7      B      null
  8      B      null

预期结果:

  No    Type  Delivery_Date

  2      B      20150120
  3      A      20150115
  4      A      20150115
  5      A      20150111
  6      A      20150112
  7      B      null
  8      B      null

在where子句中尝试了以下约束,但没有运气。

1. WHERE (DELIVERY_DATE, TYPE) IS NOT IN (NULL, 'A')
2. WHERE (NVL(DELIVERY_DATE, 0), TYPE) IS NOT IN (0, 'A')

为了使其工作,已添加名称required_row的列,如果此条件为(deliver_date为null且type =' A')并且仅选择required_row为Y的记录,则将其设置为Y.

with orders
as 
  (select 1 as no, 'A' as type, null as delivery_date from dual union 
   select 2 as no, 'B' as type, 20150120 as delivery_date from dual union  
   select 3 as no, 'A' as type, 20150115 as delivery_date from dual union 
   select 4 as no, 'A' as type, 20150115 as delivery_date from dual union 
   select 5 as no, 'A' as type, 20150111 as delivery_date from dual union
   select 6 as no, 'A' as type, 20150112 as delivery_date from dual union
   select 7 as no, 'B' as type, null as delivery_date from dual union
   select 8 as no, 'B' as type, null as delivery_date from dual
  )
   select * from ( select orders.*, 
   case when orders.delivery_date is null and type = 'A' 
        then 'N' else 'Y' 
        end as required_row from orders) where required_row='Y';

任何有关在任何其他方法中实现相同目标的任何意见/想法,保持表现,将不胜感激。

2 个答案:

答案 0 :(得分:2)

试试这个

select orders.* from orders where Delivery_Date is not null or type !='A'
 /*Assuming type as a char field and this query will output all records 
             excluding deliverydate_null with type ='A' */

修改了上述查询以包含在小提琴中共享的sql片段。

<强>更新

以下是示例 SQLFIDDLE

答案 1 :(得分:1)

可以通过不存在的子查询来解决这个问题:

SELECT * FROM order t 
WHERE not exists (
  SELECT 1 
  FROM order 
  WHERE 
    type = 'A' 
    and delivery_date is null 
    and id = t.id
)