如何将GROUP BY列分为月份和每月COUNT个?

时间:2019-04-07 03:09:41

标签: 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 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

我的输出: My output

我想要的输出如下所示: desired output

2 个答案:

答案 0 :(得分:1)

我建议使用date_part()而不是使用date_trunc()

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;

注意:

    查询中不需要
  • storestore_id存储在staff表上。
  • 在Postgres中,您可以按列别名进行聚合。
  • date_trunc()在每月的第一天产生日期列。

答案 1 :(得分:0)

您实际上需要按月和年而不是整个日期进行分组。将您的GROUP BY更改为-

const getAllStops = gql`
  query trafficStops($after: String, $before: String)  {
    trafficStops(after: $after, before: $before) {
      id
      date
    }
  }
`