问题
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