I have two tables in my Postgres DB (v14), tags and locations.
Example of tags:
id | tag_name
----+------------
1 | football
2 | tennis
3 | athletics
4 | concert
Example of locations (where tag_ids is array of ints):
id | name | tag_ids
----+--------------+------------
1 | Wimbledon | {2}
2 | Wembley | {1,4}
3 | Letzigrund | {3,4}
How can I find the name of the tags and how many times they are used? The query should result in something like this:
tag_name | count
------------+-------
football | 1
tennis | 1
athletics | 1
concert | 2
2
Answers
First flatten
locations
ast
CTE and then join withtags
.See demo.
You can do this using a join and a GROUP BY: