-2

我有这样的 Oracle sql 查询

SELECT *
FROM test
WHERE 1 =1
AND req_no IN
  (SELECT req_no
  FROM test
  WHERE date1 IS NOT NULL
  AND date1 BETWEEN '1-JUN-12' AND '30-JUN-12'
  )

问题是WHERE条件不能正常工作。在上述情况下,如果 'date1' 不为 NULL,那么我想在 'FROM' 和 'TO' 日期之间检查 'date1'。 *编辑* 我添加了示例表数据

Test table
From date: 1-JUN-2012
To date: 30-JUN-2012

record      date1          date2            date3
1       12-JUN-2012     13-JUN-2012         12-JUN-2012
2       null            null                12-JUN-2012
3       null            3-JUN-2012          null
4       12-JUN-2012     null                null
5       12-JUN-2012     13-JUL-2012         12-JUN-2012
6       null                null             null

在上面的记录中,它将返回记录号=1,2,3,4 而不是第 6 条记录。

4

4 回答 4

0

我认为您不需要子查询,您可以使用单个查询直接选择相关记录,就像您不需要检查是否date1为空一样

SELECT *  FROM test
  WHERE TO_DATE('12/2/2003','MM/DD/YYYY') <= date1 
AND TO_DATE('12/5/2003','MM/DD/YYYY') >= date1 
于 2012-09-18T05:12:17.413 回答
0

你可以OR这样使用:

WHERE date1 IS NULL
  OR date1 BETWEEN '1-JUN-12' AND '30-JUN-12'

您的整个查询应该是:

SELECT *
FROM test
WHERE 1 =1
AND req_no IN
  (SELECT req_no
  FROM test
  WHERE date1 IS NULL
  OR date1 BETWEEN '1-JUN-12' AND '30-JUN-12'
  )
于 2012-09-18T04:57:30.293 回答
0

找到了一些解决方法,但它很长

  SELECT *
FROM dates
WHERE 1  =1
AND( 
  no IN
  ( SELECT no FROM dates WHERE date1 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date2 is null and date3 is null ) 
  or 
   no IN
  ( SELECT no FROM dates WHERE date2 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date1 is null and date3 is null ) 
  or 
   no IN
  ( SELECT no FROM dates WHERE date3 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date1 is null and date2 is null ) 
   or 
   no IN
  ( SELECT no FROM dates WHERE date3 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date1 BETWEEN '1-JUN-12' AND '30-JUN-12' and date2 BETWEEN '1-JUN-12' AND '30-JUN-12' )
   or 
   no IN
  ( SELECT no FROM dates WHERE date1 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date1 BETWEEN '1-JUN-12' AND '30-JUN-12' and date3 is null )
    or 
   no IN
  ( SELECT no FROM dates WHERE date3 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date3 BETWEEN '1-JUN-12' AND '30-JUN-12' and date2 is null )
   or 
   no IN
  ( SELECT no FROM dates WHERE date2 BETWEEN '1-JUN-12' AND '30-JUN-12'
  and date3 BETWEEN '1-JUN-12' AND '30-JUN-12' and date1 is null )

  )
于 2012-09-18T06:52:48.553 回答
0

1=1是多余的。既然您说您想检查 date1 是否在日期范围之间,或者它是否为 null 也可以,请尝试:

SELECT *
FROM test
WHERE req_no IN
  (SELECT req_no
  FROM test
  WHERE date1 BETWEEN to_date('06/01/2012','mm/dd/yyyy') 
         AND to_date('06/30/2012','mm/dd/yyyy') 
        OR date1 is null
  )
于 2012-09-18T05:04:34.947 回答