PostgreSQL-每年的给定月份有多少客户活跃?

时间:2018-11-27 11:04:23

标签: sql postgresql

问题:每年的每个给定月份(例如...,2005年6月,2005年7月,.....,2006年6月等)有多少客户活跃?我们将“活跃”定义为该月内至少执行一次租借。

我进行了查询,但需要进行一些修改,这是我的查询:

SELECT rental_date, to_char(rental_date, 'Mon YYYY')
FROM rental
ORDER BY rental_date desc

我正尝试使用“ WITH”返回租金计数,并按customer_id,to_char(rental_date,'Mon YYYY')分组

Here is the ER Diagram

谢谢!

2 个答案:

答案 0 :(得分:0)

在一个月中有记录的不同的customer_id的数量:

SELECT to_char(rental_date, 'Mon YYYY'), COUNT(DISTINCT customer_id)
FROM rental
GROUP BY to_char(rental_date, 'Mon YYYY')

您需要DISTINCT,因为如果一位客户进行了3次租赁,则计数(*)为3 ..但是您询问“有多少位活跃客户”(答案:1),而不是“有多少次租赁” < / p>

答案 1 :(得分:0)

您需要GROUP BY to_char(rental_date, 'YYYY-MM')order by desc相同:

SELECT 
    to_char(rental_date, 'YYYY-MM') AS monthofyear, 
    COUNT(DISTINCT customer_id) AS activecounter 
FROM rentals
GROUP BY (to_char(rental_date, 'YYYY-MM'))
ORDER BY (to_char(rental_date, 'YYYY-MM')) DESC

此格式YYYY-MM可以正确排序。

相关问题