title: How to get distinct Weekly Active Users / distinct Monthly Active Users using a moving window / partition or any other method?
body: <p>Been cracking my skull over this, it's quite interesting though. I have a table in which each row represents an app launch event, logged from several different applications. I am using a Redshift database and therefore Redshift's implementation of Postgresql.</p>
  
  <p>Each row in this table has these columns: </p>
  
  <ul>
  <li>An application ID (app_id)</li>
  <li>A client_id which identifies a user</li>
  <li>A date (creatively named date) which is in SQL date format</li>
  </ul>
  
  <p>I need to calculate this ratio: </p>
  
  <ul>
  <li>(distinct weekly active users) / (distinct active users from the current week AND it's previous three weeks)</li>
  </ul>
  
  <p>This means, I am not looking for monthly active users as in Calendar months (Jan,Feb,Mar etc.)</p>
  
  <p>I need to calculate the distinct active users in that ISO Week divided by the active users in that week and it's previous three weeks (thus the MAU is basically past four four-week active users).</p>
  
  <p>Now, I have the query to get weekly active users as below. Week is represented as 'Week Number - Year'. </p>
  
  <pre><code>select app_id, TO_CHAR(date,'IW-IYYY') Week, count (distinct client_id) ClientsInWeek
  from weplay_singtel.gamelaunch t1
  where app_id &lt;&gt; 1751
  group by app_id, Week
  order by app_id, TO_DATE(TO_CHAR(date,'IW-IYYY'),'IW-IYYY');
  </code></pre>
  
  <p>Which gives data as shown in the attached screenshot below: <img src="https://i.stack.imgur.com/uz3GZ.png" alt="Weekly Active Users Screenshot">
  As you can see, against each ISO week and year, I have the number of distinct clients.</p>
  
  <p>To get the active users in that and the previous three weeks together, I initially used a Lag and summed the 3 previous weekly counts, for each week from the above data. However, this sum does not actually give me distinct users, it is simply a sum of distinct clients in each week. If the same user opens an app in week 1 and then again in week 2, he will be counted twice in this method, which is not acceptable!</p>
  
  <p>I need the distinct clients in a moving window of four weeks. I suspect I need to use partitions that somehow move over a week, but I cannot seem to write or visualize this query.</p>
  
  <p>Post this, I need to similarly also create the ratio: distinct Daily Active Users / distinct Active Users in the last 30 days from that day.</p>
  
  <p>Any guidance would be really helpful. Can this be done using a moving partition? Or using a Cross Apply (in Postgresql Lateral)?</p>
  
  <p>Hope this makes sense! If anything is unclear please ask and I will get back with more information almost immediately. Thanks in advance folks.</p>