I have a table which looks something like this:
table1
+----+-----+------+
| id | seq | test |
+----+-----+------+
| 1 | 1 | HR |
| 1 | 2 | RR |
| 2 | 1 | HR |
| 2 | 2 | RR |
| 2 | 3 | OXY |
| 3 | 1 | HR |
| 3 | 2 | RR |
| 4 | 1 | HR |
| 4 | 2 | RR |
| 4 | 3 | OXY |
+----+-----+------+
I would like to get the result table like below. That is I need to have all the rows of a particular id only if all the three seq number is present for a particular id:
+----+-----+------+
| id | seq | test |
+----+-----+------+
| 2 | 1 | HR |
| 2 | 2 | RR |
| 2 | 3 | OXY |
| 4 | 1 | HR |
| 4 | 2 | RR |
| 4 | 3 | OXY |
+----+-----+------+
I am looking forward to write a plpgsql function which gives me the solution. I am relatively new to plpgsql and programming in general. It would be great if someone help me out in getting the result.
So far this is what my function looks like and it is incomplete:
CREATE OR REPLACE FUNCTION test()
returns SETOF table1 AS $$
DECLARE
cur CURSOR FOR
SELECT *
FROM table1
ORDER by id;
rec_cur RECORD;
counter INTEGER DEFAULT 0;
BEGIN
OPEN cur;
FETCH FIRST FROM cur INTO rec_cur;
MOVE RELATIVE +1 FROM cur;
LOOP
FETCH cur INTO rec_cur;
EXIT WHEN NOT FOUND;
IF rec_cur.seq = 1 AND counter = 0 THEN
RETURN NEXT rec_cursor;
END IF;
END LOOP;
CLOSE cur;
RETURN;
END ; $$
LANGUAGE PLPGSQL STABLE PARALLEL SAFE;