1

我正在使用后端软件在 Oracle 上运行 SQL。我需要根据生效日期获取最新行。

这是一个示例表

Table "ACCOUNTS"
Application | Sub_category | Account_Reference | Effective_date
BC_ONLINE   | F            | ABC1234           | 01-JAN-13
BC_ONLINE   | B            | ABC2345           | 01-JAN-13
TE_Notice   | (NULL)       | 1234ABC           | 01-JAN-13
TE_Notice   | (NULL)       | 9876DEF           | 01-APR-13

软件会传入两个参数:Application和Sub_category,如果我使用下面的SQL,在下面的Application:BC_ONLINE和Sub_category:F

select a.Account_Reference
from   ACCOUNTS a
where  a.Application = 'BC_ONLINE'
and    a.Sub_category = 'F'
and    a.Effective_date = (select max(b.Effective_date)
                           from   ACCOUNTS b
                           where  b.Effective_date <= sysdate
                           and    b.Application = a.Application
                           and    b.Sub_category = a.Sub_category)

但是我应该使用以下应用程序:TE_Notice和 Sub_category: NULL 并且你不能拥有这个

and    a.Sub_category = null

因为它必须是

and    a.Sub_category is null

问题是软件是固定的,那么在使用 max(effective_date) 的 where 子句中同时使用 value 和 null 的最佳方法是什么?

我试过这个方法,但它不起作用

select a.Account_Reference
from   ACCOUNTS a
where  a.Application = 'TE_Notice'
and    (a.Sub_category = '' or a.Sub_category is null)
and    a.Effective_date = (select max(b.Effective_date)
                           from   ACCOUNTS b
                           where  b.Effective_date <= sysdate
                           and    b.Application = a.Application
                           and    NVL(b.Sub_category,-1) = NVL(a.Sub_category,-1))

它只是返回了01-APR-13的行,但我应该在01-JAN-13上得到 Effective_date 的行。

4

2 回答 2

1

怎么样:

 select account_reference
 from   (
        select   a.Account_Reference
        from     ACCOUNTS a
        where    a.Application = 'BC_ONLINE'
        and      a.Sub_category = 'F'
        and      a.effective_date <= sysdate
        order by a.Effective_date desc)
 where  rownum = 1
于 2013-02-22T12:42:31.657 回答
0

感谢@AlexPoole,我提出的问题实际上是正确的,但需要完善。

如果我采用以下内容:

and (a.Sub_category = '' or a.Sub_category is null)

选择会获取空行以及非空值,因此需要改进;

and (a.Sub_category = '' or ('' is null and a.Sub_category is null))

整体SQL应该是

select a.Account_Reference
from   ACCOUNTS a
where  a.Application = @Application
and    (a.Sub_category = @Sub_category or (@Sub_category is null and a.Sub_category is null))
and    a.Effective_date = (select max(b.Effective_date)
                           from   ACCOUNTS b
                           where  b.Effective_date <= sysdate
                           and    b.Application = a.Application
                           and    NVL(b.Sub_category,-1) = NVL(a.Sub_category,-1))
于 2013-02-22T14:35:02.807 回答