Advertisement
festinko

Untitled

Sep 28th, 2022
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.19 KB | None | 0 0
  1. /*Monthly Customers by Product Value and YearMonth*/
  2.  
  3. WITH
  4.     preparedData as (
  5.         SELECT
  6.             userID,
  7.       p.productID,
  8.       pr.productValue,
  9.             paymentAmount,
  10.             paymentPeriod,
  11.             paymentDateTime,
  12.             DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as prepaidPeriodStart,
  13.       DATE_TRUNC(DATE_ADD(DATETIME(paymentDateTime), INTERVAL paymentPeriod MONTH), MONTH) as prepaidPeriodEnd
  14.         FROM
  15.             `uptimerobot-001.ur.payments` p
  16.  
  17.     LEFT JOIN
  18.     `uptimerobot-001.ur.products` pr
  19.      
  20.       ON p.productID = pr.productID
  21.  
  22.         WHERE
  23.             paymentStatus = 1
  24.       AND paymentPeriod = 1
  25.             AND paymentPeriod BETWEEN 1 AND 12
  26.             AND userID IS NOT NULL
  27.     ),
  28.     calendar as (
  29.         select
  30.             DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as reportingYearMonth
  31.         FROM `uptimerobot-001.ur.payments`
  32.         GROUP BY reportingYearMonth
  33.     )
  34.    
  35. SELECT
  36.  cal.reportingYearMonth,
  37.  paymentPeriod,
  38.  productValue,
  39.  count(DISTINCT userID) activeCustomers
  40. FROM calendar cal
  41. JOIN preparedData pd ON cal.reportingYearMonth BETWEEN pd.prepaidPeriodStart AND prepaidPeriodEnd
  42. GROUP BY
  43.     cal.reportingYearMonth,
  44.   paymentPeriod,
  45.   productValue
  46.  
  47. ORDER BY
  48.   reportingYearMonth DESC,
  49.   paymentPeriod,
  50.   productValue
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement