I have a table with the following data:
+------------+-------------+---------------+
| shop_id | visit_date | visit_reason |
+------------+-------------+---------------+
| A | 2010-06-14 | shopping |
| A | 2010-06-15 | browsing |
| B | 2010-06-16 | shopping |
| B | 2010-06-14 | stealing |
+------------+-------------+---------------|
I need to build up an aggregate table that is grouped by shop, year, month, activity as well as total values for year and month. For example, if Shop A has 10 sales a month and 2 thefts a month and no other types of visit then the return would look like:
shop_id, year, month, reason, reason_count, month_count, year_count
A, 2010, 06, shopping, 10, 12, 144
A, 2010, 06, stealing, 2, 12, 144
Where month_count is the total number of visits, of any type, to the shop for 2010-06. Year-count is the same except for 2010.
I can get everything except the month and year counts with:
SELECT
shop_id,
extract(year from visit_date) as year,
extract(month from visit_date) as month,
visit_reason as reason,
count(visit_reason) as reason_count,
FROM shop_visits
GROUP BY shop_id, year, month
Should I be using some kind of CTE to double group by?