1

I have a table postgres that uses the array type of data, it allows some magic making it possible to avoid having more tables, but the non-standard nature of this makes it more difficult to operate with for a beginner. I would like to get some summary data out of it.

Sample content:

CREATE TABLE public.cts (
    id serial NOT NULL,
    day timestamp NULL,
    ct varchar[] NULL,
    CONSTRAINT ctrlcts_pkey PRIMARY KEY (id)
);

INSERT INTO public.cts
(id, day, ct)
VALUES(29, '2015-01-24 00:00:00.000', '{ct286,ct281}');
INSERT INTO public.cts
(id, day, ct)
VALUES(30, '2015-01-25 00:00:00.000', '{ct286,ct281}');
INSERT INTO public.cts
(id, day, ct)
VALUES(31, '2015-01-26 00:00:00.000', '{ct286,ct277,ct281}');

I would like to get the totals per array member occurence totalized, with an output like this for example:

name | value 
ct286 | 3
ct281 | 3
ct277 | 1
2
  • ct277 has a count of 1, not 2. Commented Sep 19, 2019 at 14:15
  • 1
    @gmb that's why I need a sql way to do it :) Commented Sep 19, 2019 at 14:26

1 Answer 1

3

Use Postgres function array unnest():

SELECT name, COUNT(*) cnt
FROM cts, unnest(ct) as u(name)
GROUP BY name

Demo on DB Fiddle:

| name  | cnt |
| ----- | --- |
| ct277 | 1   |
| ct281 | 3   |
| ct286 | 3   |
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.