All we need is an easy explanation of the problem, so here it is.
I have following rows in my user table as
Now I want to get user having all accesstype as view,edit and share. So I need to get two rows out of this as
How can I achieve this using postgresql statement.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
To get the rows that have exactly those three access types, you can aggregate them into an array:
select id, name, age from the_table group by id, name, age having array_agg(accesstype order by accesstype) = array['edit', 'share', 'view']
Note that the order of the elements in the
array[...] expression matters for the
= operator used because
array['a', 'b'] is not equal to
Alternatively you can use
select id, name, age from the_table group by id, name, age having bool_and(accesstype in ('edit', 'share', 'view')) and count(distinct accesstype) = 3
SELECT id, name, age FROM ( SELECT id, name, age , count(distinct accesstype) over (partition by id) as cnt FROM T WHERE accesstype IN ('view','edit','share') ) AS U WHERE cnt = 3
Assuming id, accesstype is unique you can change that to:
SELECT id, name, age FROM ( SELECT distinct id, name, age , count(accesstype) over (partition by id) as cnt FROM T WHERE accesstype IN ('view','edit','share') ) AS U WHERE cnt = 3
Untested since you did not provide a Fiddle or similar. For future posts please include something that makes it easy to reproduce your scenario.
You may also consider normalizing your tables into a separate relation for access type. Also, age is something you should derive from for example birth date. As of now, you will have to update this attribute on a regular basis (not clear on how you know when raj becomes 17 years old)
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂