PostgreSQL: How to return rows with respect to a found row (relative results)?

前端 未结 3 1477
情书的邮戳
情书的邮戳 2021-01-24 08:14

Forgive my example if it does not make sense. I\'m going to try with a simplified one to encourage more participation.

Consider a table like the following:

3条回答
  •  天命终不由人
    2021-01-24 08:39

    create table foo (dt date);
    insert into foo values
    ('2012-12-01'),
    ('2012-08-01'),
    ('2012-07-01'),
    ('2012-06-01'),
    ('2012-05-01'),
    ('2012-04-01'),
    ('2012-03-01'),
    ('2012-02-01'),
    ('2012-01-01'),
    ('1997-01-01'),
    ('2012-09-01'),
    ('2012-10-01'),
    ('2012-11-01'),
    ('2013-01-01')
    ;
    
    select dt
    from (
    (
        select dt
        from foo
        where dt <= current_date
        order by dt desc
        limit 4
    )
    union all
    (
        select dt
        from foo
        where dt > current_date
        order by dt
        limit 7
    )) s
    order by dt
    ;
         dt     
    ------------
     2012-03-01
     2012-04-01
     2012-05-01
     2012-06-01
     2012-07-01
     2012-08-01
     2012-09-01
     2012-10-01
     2012-11-01
     2012-12-01
     2013-01-01
    (11 rows)
    

提交回复
热议问题