如果value等于最后一行,则Postgresql Skip Row

时间:2014-02-20 21:58:00

标签: sql postgresql

Postgres 9.1中的

如果NAME的值等于f.e之前的值,则可以跳过行。下表

ID | NAME | AGE | SEX | CLASS
---------------------------------
1    Paul   17    M     2b
2    Paul   16    M     2b
3    Paul   18    F     2b
4    Lexi   18    M     2b
5    Sarah  16    F     2b
6    Sarah  17    F     2b

结果应为:

1    Paul   17    M     2b
4    Lexi   18    M     2b
5    Sarah  16    F     2b

感谢您的帮助,

t book

2 个答案:

答案 0 :(得分:4)

select *
from (
  select id, 
         name, 
         age, 
         sex, 
         class, 
         lag(name) over (order by id) as prev_name
  from the_table
) as t
where name <> prev_name;

替代地

select *
from (
  select id, 
         name, 
         age, 
         sex, 
         class, 
         row_number() over (partition by name order by id) as rn
  from the_table
) as t
where rn = 1;

另一种选择是使用Postgres'distinct on运算符:

select distinct on (name) 
       id, 
       name,
       age,
       sex,
       class
from the_table
order by name,id

但是这将返回name排序的结果(这是distinct on运算符的限制)。如果你不想要,你需要再次包装它:

select *
from (
  select distinct on (name) 
         id, 
         name,
         age,
         sex,
         class
  from the_table
  order by name,id
) t
order by id;

答案 1 :(得分:1)

SELECT ID , NAME , AGE , SEX , CLASS
FROM thetable t
WHERE NOT EXISTS (
    SELECT * FROM thetable nx
    WHERE nx.NAME = t.NAME
    -- AND nx.ID < t.ID -- ANY one before it
    AND nx.ID = t.ID-1  -- THE one before it
    );