SQL 获取按最新修改行排序的分组字段

SQL get grouped field ordered by lastest modified row

我有一个 table 文档(id、名称、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)

有什么想法吗?

谢谢

试试这个:

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 中创建了一个演示。

如果我没猜错,你想return为每个权宜之计

排一行
SELECT id_expedient 
  FROM (SELECT id_expedient, max(NVL(modify_date, creation_date))
    FROM document
    GROUP BY id_expedient
        );

http://sqlfiddle.com/#!4/53997f/15