3

Given the following table

  grp |   ind |   val
----------------------
    a |     1 |     1
    a |     2 |     1
    a |     3 |     1
    a |     4 |     2
    a |     5 |     2
    a |     6 |     4
    a |     7 |     2
    b |     1 |     1
    b |     2 |     1
    b |     3 |     1
    b |     4 |     3
    b |     5 |     3
    b |     6 |     4

I need to select the following:

  grp |   ind |   val
----------------------
    a |     1 |     1
    a |     4 |     2
    a |     6 |     4
    a |     7 |     2
    b |     1 |     1
    b |     4 |     3
    b |     6 |     4

That is for each 'grp', each record where the 'val' is different to the proceeding 'val' (ordered by 'index') So each record where the 'value' "steps".

what would be the most efficient way to achieve this?

thanks.

Here is a script to create the test case:

create temp table test_table
(
    grp character varying,
    ind numeric,
    val numeric
);
insert into test_table values
    ('a', 1 , 1),
    ('a', 2 , 1),
    ('a', 3 , 1),
    ('a', 4 , 2),
    ('a', 5 , 2),
    ('a', 6 , 4),
    ('a', 7 , 2),
    ('b', 1 , 1),
    ('b', 2 , 1),
    ('b', 3 , 1),
    ('b', 4 , 3),
    ('b', 5 , 3),
    ('b', 6 , 4);
4

3 回答 3

2
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE ztable
        ( zgroup CHAR(1)
        , zindex int
        , zvalue INTEGER
        );
INSERT INTO ztable(zgroup,zindex,zvalue) VALUES
    ('a',     1,      1)
    ,('a',     2,      1)
    ,('a',     3,      1)
    ,('a',     4,      2)
    ,('a',     5,      2)
    ,('a',     6,      4)
    ,('b',     1,      1)
    ,('b',     2,      1)
    ,('b',     3,      1)
    ,('b',     4,      3)
    ,('b',     5,      3)
    ,('b',     6,      4)
        ;

WITH agg AS (
        SELECT zgroup
        , zindex
        , zvalue
        , row_number() OVER (PARTITION BY zgroup ORDER BY zindex) AS zrank
        FROM ztable
        )
SELECT t1.zgroup,t1.zindex,t1.zvalue
FROM agg t1
LEFT JOIN agg t0 ON t0.zgroup = t1.zgroup AND 1+t0.zrank = t1.zrank
WHERE t0.zvalue <> t1.zvalue OR t0.zrank IS NULL
        ;
于 2012-07-18T10:46:59.137 回答
2
select grp,
       ind,
       val
from (
   select grp, 
          ind, 
          val,
          lag(val,1,0::numeric) over (partition by grp order by ind) - val as diff
   from test_table
) t
where diff <> 0;
于 2012-07-18T10:55:50.093 回答
1
select group,min(index) as index,value from table
group by group,value
于 2012-07-18T10:31:26.577 回答