how to get a single row based on my condition

All we need is an easy explanation of the problem, so here it is.

I have following rows in my user table as

how to get a single row based on my condition

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 to get a single row based on my condition

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.

Method 1

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 array['b', 'a'].

Alternatively you can use bool_and()

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

Method 2

Something like:

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 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply