我有一个包含以下数据的表:
+------------+-------------+---------------+
| 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 |
+------------+-------------+---------------|
我需要建立一个汇总表,该表按商店,年,月,活动以及年和月的总值分组。例如,如果商店A每月有10次销售,每月有2次盗窃,并且没有其他类型的访问,那么回报将是:
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
其中month_count是2010-06年该商店的任何类型的访问总次数。除2010年外,年数相同。
我可以使用以下方法获得除月份和年份之外的所有内容:
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
我应该使用某种CTE分组吗?
答案 0 :(得分:1)
您可以使用窗口功能来累加计数。以下是使用date_trunc()
的短语,我发现按月进行汇总更方便:
select shop_id, date_trunc('month', visit_date) as yyyymm, reason,
count(*) as month_count,
sum(count(*)) over (partition by shop_id, date_trunc('year', min(visit_date))) as year_count
from t
group by shop_id, date_trunc('month', visit_date), reason;