Hi I’m having trouble with query in PostgreSQL . Here is example data from my table imgs_tags
:
x
img_id | tag_id
1 2
1 3
2 2
2 3
3 2
3 3
I had tried :
select count(img_id) from imgs_tags where tag_id IN(2,3) group by img_id having count(tag_id) = 2
and it returns as below :
count:
2
2
2
But I want it to return count = 3
. How can i fix it ? Thanks
Advertisement
Answer
You should write like this:
select count(*) from (
select img_id
from imgs_tags
where tag_id IN (2,3)
group by img_id
having count(tag_id) = 2
) t
or if you want to do some further operation with this data then better use Common Table Expression (with clause)
like below:
with cte as (
select img_id
from imgs_tags
where tag_id IN (2,3)
group by img_id
having count(tag_id) = 2
)
select count(*) from cte