[英]count rows with group by and having count (postgres)
嗨,我在 PostgreSQL 中查詢時遇到問題。 這是我的表imgs_tags
示例數據:
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;
returns
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
或者如果你想對這些數據做一些進一步的操作,那么更好地使用Common Table Expression (with clause)
如下所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.