0

My goal is to create a condition where the number of unique rows equals 3 or more,

For an instance - if I got the result:

| id | 
1
2
3

then there are 3 rows return true. (for the existence part I'll use EXISTS)

I've tried to use COUNT(*) and DISTINCT to count all the different unique rows, but as I want to use condition -

  • using WHERE is impossible due the COUNT function
  • nor using HAVING - because there's a need to use GROUP BY first, which cause the COUNT(*)=1.

Another requirement - is to use postgresql at version 9.4

My latest attempt which returns nothing because COUNT(*)=1

exists(
     select count(*)
     from (select sid, bno
           from schedule scj inner join revent on scj.eid = revent.reid
           where 12345 = cno AND 'hello' = sid) as foo
     group by sid, bno
     having count(*)>=3)
2
  • what result do you want? different rules apply to conditions in different contexts. Commented Jul 29, 2018 at 19:31
  • The result I was looking for on this question was a boolean value, as my final query is more complex than that, therefore - I was trying to simplify the question. Commented Jul 29, 2018 at 19:37

1 Answer 1

1

You would use:

select (count(*) >= 3)
from result;

result could be a CTE, subquery, or other query logic that generates the rows in your first result set.

So, if this is your query:

select sid, bno
from schedule scj inner join revent on scj.eid = revent.reid
where 12345 = cno AND 'hello' = sid

Then the logic is:

select (count(*) >= 3)
from (select sid, bno
      from schedule scj inner join revent on scj.eid = revent.reid
      where 12345 = cno AND 'hello' = sid
     ) result;
Sign up to request clarification or add additional context in comments.

1 Comment

Look like it works, good to know there also conditions on the SELECT section, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.