How to get count from mapping table group be another table in PostgreSQL?

雨燕双飞 提交于 2019-12-25 07:27:09

问题


I have three tables:

store 
=====
   name
   address 
   city 
   state 
   country 
   tag ..., 

post
=======
    title
    summary 
    tags ...

store_post_map
================
(mapping on store and post based on tag).

Now I want to get count of posts from mapping table group by city, state, country or store.id, what to be the SQL in PostgreSQL?


回答1:


Basically, it's this:

SELECT store_id, count(*) AS posts_ct
FROM   store_post_map
GROUP  BY store_id;

How can we get counts for each city, state or country where each area can have multiple stores?

Count per country:

SELECT s.country, count(*) AS posts_ct
FROM   store          s
JOIN   store_post_map sp ON sp.store_id = s.id
GROUP  BY 1; -- positional parameter - is the same as GROUP BY s.country here

For the count per city you may have to GROUP BY area and country in addition since a city name is hardly unique. Like:

SELECT s.city, s.area, s.country, count(*) AS posts_ct
FROM   store          s
JOIN   store_post_map sp ON sp.store_id = s.id
GROUP  BY 1, 2, 3;


来源:https://stackoverflow.com/questions/14871316/how-to-get-count-from-mapping-table-group-be-another-table-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!