DROP TABLE IF EXISTS thing;

CREATE TABLE thing
  (
    id         int        NOT NULL,
    thing_id   int        NOT NULL,
    category   varchar(1) NOT NULL,
    period_id  int        NOT NULL
  );

COPY thing FROM STDIN;
1	1	A	1
2	1	A	2
3	1	A	3
4	1	A	4
5	1	B	5
6	1	B	6
7	1	B	7
8	1	A	8
9	1	A	9
10	2	A	1
11	2	A	2
12	2	A	3
13	2	A	4
\.

SELECT
    thing_id,
    category,
    int4range_list(period_id)
  FROM thing
  GROUP BY thing_id, category
  ORDER BY 1, 2;

TRUNCATE TABLE thing;

COPY thing FROM STDIN;
1	1	A	1
2	1	A	2
3	1	A	3
4	1	A	7
5	1	A	8
6	1	A	9
7	2	A	1
8	2	A	2
9	2	A	3
10	2	A	4
\.

SELECT
    thing_id,
    category,
    int4range_list(period_id)
  FROM thing
  GROUP BY thing_id, category
  ORDER BY 1, 2;
