2014-11-01 70 views
0

我有表friendbook_post与属性text,id,author,type,date_timeid是主键,表中有很多条目。如何从另一个属性中具有相同值的表中获取第一个和最后一个值?

作者可以创建任意数量的帖子,即'author'在多行中可以相同。

现在我想获取每个作者根据date('date_time')制作的第一个和最后一个post(text)以及日期。

我想这很多查询,但没有得到预期的结果。

请帮我用oracle RDBMS。

+0

删除'mysql'标签基于“帮我拿出甲骨文” – 2014-11-01 13:07:18

回答

1

也许你想是这样的:

select fp.* 
from friendbook_post fp join 
    (select fp.author, min(fp.id) as minid, max(fp.id) as maxid 
     from friendbook_post 
     group by fp.author 
    ) a 
    on fp.author = a.author and fp.id in (a.minid, a.maxid); 
1
select id, text, author, type, date_time, 
from (
    select text, id, author, type, date_time, 
     row_number() over (partition by author order by date_time) as rn, 
     count(*) over (partition by author) as total_author_posts 
    from friendbook_post 
) t 
where rn = 1 
    or rn = total_author_posts; 

相反,如果你想在同一个最大或最小日期多个职位退货:

select id, text, author, type, date_time, 
from (
    select text, id, author, type, date_time, 
     max(date_time) over (partition by author) as max_date, 
     min(date_time) over (partition by author) as min_date 
    from friendbook_post 
) t 
where date_time = max_date 
    or date_time = min_date; 

顺便说一句:date_time是一个可怕的名字。它没有记录是什么样的“日期时间”。删除时间?发布时间?发布时间? “最后更改的时间”?

相关问题