【问题标题】:PostgreSQL - How many customers are active at any given month per year?PostgreSQL - 每年任何给定月份有多少活跃客户?
【发布时间】:2019-04-29 02:38:59
【问题描述】:

问题:每年任何给定月份有多少活跃客户(例如 ...、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

谢谢!

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    当月有记录的不同 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),而不是“执行了多少次租赁”

    【讨论】:

      【解决方案2】:

      你需要GROUP BYto_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可以正确排序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-11
        • 2020-09-13
        • 2020-10-06
        • 1970-01-01
        相关资源
        最近更新 更多