【问题标题】:SQL to find the distribution of monthly frequency of customers for the year 2022SQL查找2022年客户每月频率分布
【发布时间】:2023-01-24 15:45:36
【问题描述】:

我有一个交易表,其中包含 transaction_id 和 customer_id,交易日期为 transaction_date。我想找到 2022 年客户每月频率的分布。任何帮助将不胜感激,因为我是数据科学和分析的新手。

【问题讨论】:

  • 请提供一些示例数据和预期结果,作为问题中带有文本的表格。还要解释您尝试过的内容以及具体没有按预期工作的内容。请记住,SO 不是代码编写服务。
  • 分享您尝试过的查询

标签: sql sql-server


【解决方案1】:

您是否正在寻找这样的东西:

SELECT MONTH([date])
      ,COUNT(customer_id) -- customers per month
      ,COUNT(DISTINCT customer_id) -- unique customers per month
FROM [transaction]
WHERE YEAR([date]) = 2022
GROUP BY MONTH([date])

以上将为您提供每月的客户总数。如果您需要向下钻取并查找每个客户每月的交易:

SELECT customer_id
      ,MONTH([date])
      ,COUNT(transaction_id)
FROM [transaction]
WHERE YEAR([date]) = 2022
GROUP BY customer_id

【讨论】:

    【解决方案2】:

    要查找 2022 年客户的每月频率分布,您可以使用以下步骤:

    1. 使用 DATE_TRUNC 或 DATE_EXTRACT 函数从 transaction_date 列中提取年份和月份。
    2. 使用 WHERE 子句过滤表以仅包含 2022 年发生的交易。
    3. 按 customer_id 和提取的分组剩余交易 月。
    4. 使用 COUNT() 函数计算每个交易的数量 客户每月。
    5. 使用 GROUP BY 子句按提取的月份对结果进行分组。
    6. 再次使用 COUNT() 函数来计算客户数量 每个月都有交易。

      示例代码:

         WITH transactions_2022 AS (
                  SELECT customer_id,
                         DATE_TRUNC('month', transaction_date) AS month,
                         COUNT(transaction_id) as frequency
                  FROM transactions
                  WHERE DATE_TRUNC('year', transaction_date) = '2022'
                  GROUP BY 1,2
              )
              SELECT month,
                     COUNT(DISTINCT customer_id) as customer_count,
                     SUM(frequency) as transaction_count
              FROM transactions_2022
              GROUP BY 1
         
      

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2022-07-11
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多