如何限制我的sql select只返回一行max(date),而不是多行?

时间:2017-04-05 14:29:46

标签: sql oracle

我正在尝试只选择一个具有最新日期列的id,但此sql查询返回多行。我怎样才能选择最新的? MAX()似乎不起作用

select ra.sourceid as partner1, max(ra.date) from ra_table ra join rap_table rap on parentid=ra.sourceid
where (ra.type = 'Normal' and (ra.name IS NOT NULL or ra.parent IS NOT NULL) and rap.createdate > ra.createdate)
group by ra.sourceid
;

5 个答案:

答案 0 :(得分:1)

在Oracle 12c或更高版本上:

select ra.sourceid as partner1, 
    ra.date
from ra_table ra 
join rap_table rap
    on parentid=ra.sourceid
where (ra.type = 'Normal' 
    and (ra.name IS NOT NULL or ra.parent IS NOT NULL) 
    and rap.createdate > ra.createdate)
order by ra.date desc
fetch first row only;

在12c之前的Oracle上:

select *
from (
    select ra.sourceid as partner1, 
        ra.date
    from ra_table ra 
    join rap_table rap
        on parentid=ra.sourceid
    where (ra.type = 'Normal' 
        and (ra.name IS NOT NULL or ra.parent IS NOT NULL) 
        and rap.createdate > ra.createdate)
    order by ra.date desc
    )
where rownum = 1

此处的两个查询都将返回结果中最新日期值的ID和日期。没有必要聚合,因为我们确定要返回什么类型,我们只想要一行。

答案 1 :(得分:0)

在您的情况下不确定它是否正确,但最后SELECT FIRST 1 ROWS ONLY可以提供帮助。

答案 2 :(得分:0)

您可以使用MIN( sourceid ) KEEP ( DENSE_RANK FIRST ORDER BY ra.date DESC )获取最高sourceid值的最低date

SELECT MIN( ra.sourceid ) KEEP ( DENSE_RANK FIRST ORDER BY ra.date DESC ) as partner1,
       max(ra.date)
from   ra_table ra
       join rap_table rap
       on parentid=ra.sourceid
where  ra.type = 'Normal'
and    (ra.name IS NOT NULL or ra.parent IS NOT NULL)
and    rap.createdate > ra.createdate;

答案 3 :(得分:-1)

您可以在查询中按降序使用前1:

select Top 1 ra.sourceid as partner1, max(ra.date) from ra_table ra join rap_table rap on parentid=ra.sourceid
where (ra.type = 'Normal' and (ra.name IS NOT NULL or ra.parent IS NOT NULL) and rap.createdate > ra.createdate)
group by ra.sourceid order by max(ra.date) desc

答案 4 :(得分:-1)

MAX()是一个按功能分组,因此如果您要求多个列,它将为您提供最大的唯一组合。当您在查询中使用ID列时,您总是会获得唯一身份(违背最大目的)。

您应该稍微调整一下您的查询:

select TOP 1 ra.sourceid as partner1 FROM ra_table ra 
WHERE ra.date = (SELECT  max(ra.date) 
from 
    ra_table ra 
    join rap_table rap on parentid=ra.sourceid
where 
    (ra.type = 'Normal' and (ra.name IS NOT NULL or ra.parent IS NOT NULL) and rap.createdate > ra.createdate)
group by ra.sourceid)