Advertisement
festinko

Untitled

Sep 27th, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 0.93 KB | None | 0 0
  1. WITH
  2.     preparedData as (
  3.         SELECT
  4.             userID,
  5.       productID,
  6.             paymentAmount,
  7.             paymentPeriod,
  8.             paymentDateTime,
  9.             DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as prepaidPeriodStart,
  10.       DATE_TRUNC(DATE_ADD(DATETIME(paymentDateTime), INTERVAL paymentPeriod MONTH), MONTH) as prepaidPeriodEnd
  11.         FROM
  12.             `uptimerobot-001.ur.payments`
  13.         WHERE
  14.             paymentStatus = 1
  15.             AND paymentPeriod BETWEEN 1 AND 12
  16.             AND userID IS NOT NULL
  17.     ),
  18.     calendar as (
  19.         select
  20.             DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as reportingYearMonth
  21.         FROM `uptimerobot-001.ur.payments`
  22.         GROUP BY reportingYearMonth
  23.     )
  24.    
  25. SELECT
  26.  cal.reportingYearMonth,
  27.  paymentPeriod,
  28.  count(DISTINCT userID) activeCustomers
  29. FROM calendar cal
  30. JOIN preparedData pd ON cal.reportingYearMonth BETWEEN pd.prepaidPeriodStart AND prepaidPeriodEnd
  31. GROUP BY
  32.     cal.reportingYearMonth,
  33.   paymentPeriod
  34.  
  35. ORDER BY
  36.   reportingYearMonth DESC,
  37.   paymentPeriod
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement