我正在使用后端软件在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,则在以下应用程序中: 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的行。
答案 0 :(得分: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
答案 1 :(得分:0)
感谢@AlexPoole我在问题中提出的SQL实际上是正确的,但需要抛光。
如果我采纳了以下内容:
and (a.Sub_category = '' or a.Sub_category is null)
select将获取空行以及非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))