postgresql 从上个月的活动用户列表中识别非活动用户

mzsu5hc0  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(139)

考虑以下CTE。它们正确地为我提供了每月活动用户的列表。但是,对于非活动用户,它们返回无效的用户ID。对于每个月(例如,2023-09)的“非活动用户”,我指的是在上个月(2023-08)期间活动但在下一个/当前月份(2023-09)不活动的用户。

WITH payments AS (
  SELECT "UserId", DATE_TRUNC('month', "PayDate") AS "Month"
  FROM "public"."Payments"
  WHERE "IsPaid" = TRUE
     AND "IsDeleted" = FALSE 
     AND "PayDate" BETWEEN {{START_DATE}} AND {{END_DATE}}
),

active_users AS (
  SELECT "Month", "UserId"
  FROM payments
  GROUP BY "Month", "UserId"
),

inactive_users AS (
  SELECT previous_month."Month" + INTERVAL '1 month' AS "Month", previous_month."UserId"
  FROM active_users AS previous_month
  WHERE NOT EXISTS (
    SELECT 1
    FROM active_users AS current_month
    WHERE previous_month."UserId" = current_month."UserId"
      AND current_month."Month" = (previous_month."Month" + INTERVAL '1 month')
  )
)

字符串
我需要的最终结果集,包括唯一的用户和他们相应的月份列表。

编辑

WITH payments AS (
  SELECT "UserId", DATE_TRUNC('month', "PayDate") AS "Month"
  FROM "public"."Payments"
  WHERE "IsPaid" = TRUE
     AND "IsDeleted" = FALSE 
     AND "PayDate" BETWEEN '2023-07-01' AND '2023-12-01'
),

active_users AS (
  SELECT DISTINCT "Month", "UserId"
  FROM payments
),

inactive_users AS (
  SELECT a."UserId", a."Month"
  FROM active_users a
  WHERE NOT EXISTS (
    SELECT 1
    FROM payments b
    WHERE a."UserId" = b."UserId" AND (a."Month" + INTERVAL '1 month') = b."Month"
  )
)

SELECT * FROM inactive_users

uyto3xhc

uyto3xhc1#

1.而不是CTE active_users AS..
1.在最后的CTE中,EXISTS子句应该查询“public”.“Payments”表。

相关问题