How can we find the occurrence count to position mapping for elements in an array type in postgres ?
For example:
["A", "B", "C", "D"]
["A", "B", "C", "D"]
["A", "B", "D", "C"]
["A", "D", "C", "B"]
Should yield
| Element | Position | Occurrences |
|---|---|---|
| A | 1 | 4 |
| A | 2 | 0 |
| A | 3 | 0 |
| A | 4 | 0 |
| B | 1 | 0 |
| B | 2 | 3 |
| B | 3 | 0 |
| B | 4 | 1 |
| C | 1 | 0 |
| C | 2 | 0 |
| C | 3 | 3 |
| C | 4 | 1 |
| D | 1 | 0 |
| D | 2 | 1 |
| D | 3 | 1 |
| D | 4 | 2 |
I know about that array_position can get the position (1-based) but I am stumped as to how to achieve what I want ?
SQL Query:
create table test (id integer, priorities varchar(100)[]);
insert into test (id, priorities) values (1, '{"A","B","C","D"}');
insert into test (id, priorities) values (2, '{"A","B","C","D"}');
insert into test (id, priorities) values (3, '{"A","D","C","B"}');
insert into test (id, priorities) values (4, '{"A","C","B","D"}');
Edit #1: I think I can somehow combine unnest with ordinality and group by to achieve this.