Postgresql ver 15
Let’s say I have a list of values, e.g.
ID
alpha
beta
delta
.
.
.
and I wish to check for each value, whether such a value exists in every group that is partitioned in a table, e.g.
GROUP ID
A alpha
A aplha
B alpha
B peanuts
...
In the above table, let’s assume the id alpha
is in every group, so that check is true.
How do I do this check? Appreciate any advice given on how to start.
2
Answers
You can use PostgreSQL Except function to do that.
First, find out how many group we have,
Then, find out a list of ID exists in every group,
Lastly, compare it with the master ID list using Except function.
If there is any ID shown in the result, those are the ones NOT in every group.
See the following code as example
another way to use window function in PostgreSQL
See the following code as example
First
cte
is to getDistinct
Groups and total number of groups, then on the secondcte
we applycross join
to the ID that we are looking for, then aninner join
to check if the total number match with count of the rows that satisfies both the table :Demo here