开发者

can this be done in one sql query?

开发者 https://www.devze.com 2023-02-08 10:04 出处:网络
table indexed on the field name for given value of name \"name1\" give me that row开发者_Go百科 as well as N rows before and N rows after (alphabetically)Did it in two select statements replace the n

table indexed on the field name

for given value of name "name1" give me that row开发者_Go百科 as well as N rows before and N rows after (alphabetically)


Did it in two select statements replace the number 5 with whatever you want you N to be and change the table name and this will do it. Also replace the asterisk with correct column names. Let me know if you have any problems with this.

  select * from 
    (
        Select *
        ,row_number() over (order by firstname desc) as 'rowNumber'
        from attendees
    ) as temp
where rowNumber between 
 (
    select rownumber-1 
    from 
        (
            Select *, row_number() over (order by firstname desc) as 'rowNumber'
            from attendees
        ) as temp
    where firstname = 'name1')  AND (
    select rownumber+1 
    from 
        (
            Select *, row_number() over (order by firstname desc) as 'rowNumber'
            from attendees
        ) as temp
    where firstname = 'name1')


The following gets you the row with name = 'name4', the two rows before that, and the two rows after that.

drop table t;

create table t(
   name varchar(20)
  ,primary key(name)
);

insert into t(name) values('name1');
insert into t(name) values('name2');
insert into t(name) values('name3');
insert into t(name) values('name4');
insert into t(name) values('name5');
insert into t(name) values('name6');
insert into t(name) values('name7');

commit;

(select name from t where name = 'name4')
  union all
(select name from t where name > 'name4' order by name asc  limit 2)
  union all
(select name from t where name < 'name4' order by name desc limit 2);


 +-------+
 | name  |
 +-------+
 | name1 |
 | name2 |
 | name4 |
 | name5 |
 | name6 |
 +-------+

Edit: Added descending order by as pointed out by cyberkiwi (otherwise I would have gotten the "first" 2 items on the wrong end).

0

精彩评论

暂无评论...
验证码 换一张
取 消