Advertisement
festinko

Untitled

Dec 13th, 2022
657
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.58 KB | None | 0 0
  1. /*Churned Customers Monthly*/
  2. WITH
  3.     preparedData as (
  4.         SELECT
  5.             p.userID,
  6.       p.productID,
  7.       pr.productValue,
  8.             paymentAmount,
  9.             paymentPeriod,
  10.             paymentDateTime,
  11.             DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as prepaidPeriodStart,
  12.       DATE_TRUNC(DATE_ADD(DATETIME(paymentDateTime), INTERVAL paymentPeriod MONTH), MONTH) as prepaidPeriodEnd,
  13.       DATE_TRUNC(DATE_ADD(DATETIME(paymentDateTime), INTERVAL paymentPeriod MONTH), DAY) as prepaidPeriodEndDay
  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.         LEFT JOIN   (
  23.             SELECT
  24.                 userID,
  25.                 MAX(paymentDateTime) lastPaymentDateTime
  26.             FROM
  27.                 `uptimerobot-001.ur.payments`
  28.            
  29.             WHERE
  30.                 paymentStatus = 1
  31.                 AND paymentPeriod IN (1,12)
  32.                 AND userID IS NOT NULL
  33.             GROUP BY
  34.                 userID
  35.             ) lp
  36.             ON p.userID =lp.userID AND p.paymentDateTime = lp.lastPaymentDateTime
  37.  
  38.         WHERE
  39.             paymentStatus = 1
  40.             AND paymentPeriod IN (1,12)
  41.             AND p.userID IS NOT NULL
  42.             AND lp.lastPaymentDateTime IS NOT NULL
  43.     ),
  44.     calendar as (
  45.         SELECT
  46.         DATE_TRUNC(DATETIME(paymentDateTime), MONTH) as reportingYearMonth
  47.         FROM `uptimerobot-001.ur.payments`
  48.         GROUP BY reportingYearMonth
  49.     )
  50.  
  51.   SELECT
  52.         reportingYearMonth,
  53.         COUNT(DISTINCT userID)
  54.  
  55.   FROM
  56.     preparedData pd
  57.    
  58.     LEFT JOIN calendar cal
  59.         ON pd.prepaidPeriodEndDay > reportingYearMonth AND pd.prepaidPeriodEndDay < DATE_ADD(cal.reportingYearMonth, INTERVAL 1 MONTH)
  60.    
  61.     GROUP BY
  62.         reportingYearMonth
  63.    
  64.     ORDER BY
  65.         reportingYearMonth DESC
  66.  
  67.  
  68.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement