我有一个表文档(id,name,id_expedient,creation_date,modify_date)。权宜之计可以有几个文件。 我有一个文档ID,我想找到一个权宜之计,其最后修改(或创建)的文档是我在Oracle SQL中选择的文档
例如
id name id_expedient creation_date modify_date
----------------------------------------------------------------------
1 doc Monday exp A 2/11/2015
2 doc Tuesday exp B 2/10/2015
3 doc Friday exp C 2/09/2015
4 doc Thursday exp C 2/01/2015 2/08/2015
如果我搜索文件ID:
1 the result must be Exp A
2 the result must be Exp B
3 the result must be Exp C
4 the result must be void, because doc Thursday is not the lastest modified document of Exp C (that would be doc 3)
我尝试过子查询,但我无法获得最新的权宜之计
SELECT id_exp
from TB_DOCUMENT doc1
where doc1.doc_id IN
(select TOP 1 DOC2.doc_id FROM
(SELECT DOC2.doc_id, NVL(MODIFY_DATE,CREATION_DATE) AS DateC
FROM TB_DOCUMENT DOC2
WHERE DOC2.id_exp = doc1.id_exp)
ORDER by DateC DESC)
有什么想法吗?
谢谢
答案 0 :(得分:2)
试试这个:
select *
from TB_DOCUMENT t
where (id_expedient,
coalesce(modify_date,
creation_date
)
) in (select id_expedient,
max(coalesce(modify_date, creation_date))
from TB_DOCUMENT sub
where t.id_expedient = sub.id_expedient
group by id_expedient)
and t.id = YOUR_ID
where条件中的子查询允许您仅获取每个id_expedient
具有最大创建或修改日期的行。
我在SQLFiddler创建了一个演示。
答案 1 :(得分:0)
如果我做对了,你想为每个权宜之计
返回一行SELECT id_expedient
FROM (SELECT id_expedient, max(NVL(modify_date, creation_date))
FROM document
GROUP BY id_expedient
);