Sql 使用group by和count(postgres)对行进行计数

Sql 使用group by和count(postgres)对行进行计数,sql,postgresql,Sql,Postgresql,您好,我在PostgreSQL查询方面遇到了问题。下面是我的表格imgs\u标签中的示例数据: img_id | tag_id 1 2 1 3 2 2 2 3 3 2 3 3 我试过: select count(img_id) from imgs_tags where tag_id IN(2,3) group by img_id having count(tag_id) =

您好,我在PostgreSQL查询方面遇到了问题。下面是我的表格
imgs\u标签
中的示例数据:

img_id | tag_id
   1        2
   1        3
   2        2
   2        3
   3        2
   3        3
我试过:

select count(img_id) from imgs_tags where tag_id IN(2,3) group by img_id having count(tag_id) = 2
它返回如下所示:

count:
  2
  2 
  2

但我希望它返回
count=3
。我怎样才能修好它?谢谢

您可以像这样使用子查询

select count(*) from (select count(img_id) from imgs_tags where tag_id IN(2,3) group by img_id having count(tag_id) = 2) as temp_img_tags;

返回
3

您可以像这样使用子查询

select count(*) from (select count(img_id) from imgs_tags where tag_id IN(2,3) group by img_id having count(tag_id) = 2) as temp_img_tags;

返回
3您应该这样写:

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
或者,如果您想对这些数据执行进一步的操作,最好使用
公共表表达式(with子句)
如下所示:

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

你应该这样写:

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
或者,如果您想对这些数据执行进一步的操作,最好使用
公共表表达式(with子句)
如下所示:

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

看起来像三排。。。你能编辑问题并添加你期望的输出吗?看起来像3行。。。您是否可以编辑问题并添加预期输出?