Sql 如何按列将月份分组并按月计数?

Sql 如何按列将月份分组并按月计数?,sql,postgresql,Sql,Postgresql,我试图返回每个商店每月完成的租赁订单数量。我想展示四个栏目;月、年、店铺ID、租金计数(每月)。我可以返回月、年和店铺ID列,但租金不按月计算: SELECT DATE_PART('month', r.rental_date) Rental_month, DATE_PART('year', r.rental_date) Rental_year, s.store_id, COUNT(r.rental_date) count_rentals FROM store s JOIN staff

我试图返回每个商店每月完成的租赁订单数量。我想展示四个栏目;月、年、店铺ID、租金计数(每月)。我可以返回月、年和店铺ID列,但租金不按月计算:

SELECT 
DATE_PART('month', r.rental_date) Rental_month, 
DATE_PART('year', r.rental_date) Rental_year, 
s.store_id, 
COUNT(r.rental_date) count_rentals 
FROM store s
JOIN staff staf
ON s.store_id = staf.store_id
JOIN payment pay
ON staf.staff_id = pay.staff_id
JOIN rental r
ON pay.rental_id = r.rental_id
GROUP BY r.rental_date, s.store_id
我的输出:

我期望的输出如下所示:

您需要实际按月份和年份分组,而不是按完整日期分组。将您的组更改为-

GROUP BY  
       DATE_PART('month', r.rental_date),
       DATE_PART('year', r.rental_date),
       s.store_id,

我建议使用
date\u-part()
,而不是
date\u-trunc()

注:

  • 查询中不需要存储。
    store\u id
    存储在
    staff
    表中
  • 在Postgres中,可以通过列别名进行聚合
  • date\u trunc()
    在每月的第一天生成一个日期列
1x
date\u drunc()
>>2x
date\u part()
SELECT DATE_TRUNC('month', r.rental_date) as yyyymm, 
       st.store_id, 
       COUNT(*) as count_rentals 
FROM staff st JOIN
     payment p
     ON st.staff_id = p.staff_id JOIN
     rental r
     ON p.rental_id = r.rental_id
GROUP BY yyyymm, st.store_id;