2021年1月5日星期二

How to perform sql group by week and count of users who are created >= the week (Not just in that week)?

Example:

| Week | UserId |  | ---- | ------ |  | 0    | A      |  | 0    | B      |  | 0    | C      |  | 1    | D      |  | 1    | E      |  | 1    | F      |  | 2    | G      |  | 3    | H      |  | 3    | I      |  

Now I want the table like below

| Week | Users |  | ---- | ------ |  | 0    | 9      |  | 1    | 6      |  | 2    | 3      |  | 3    | 2      |  

Now I could use

    *  FROM (     week_3_users AS (      SELECT DISTINCT User_ID      FROM users      WHERE week >= 3    ),     week_2_users AS (      SELECT DISTINCT User_ID      FROM users      WHEREweek >= 2    ),     week_1_users AS (      SELECT DISTINCT User_ID      FROM users      WHERE week >= 1    ),    week_0_users AS (      SELECT DISTINCT User_ID      FROM users      WHERE week >= 0    )    SELECT     (SELECT count(*) FROM week_0_users) AS week_0_count,    (SELECT count(*) FROM week_1_users JOIN week_0_users USING (User_ID)) AS week_1_count,    (SELECT count(*) FROM week_2_users JOIN week_0_users USING (User_ID)) AS week_2_count,    (SELECT count(*) FROM week_3_users JOIN week_0_users USING (User_ID)) AS week_3_count  )  

That gives me

| week_0_count | week_1_count | week_2_count | week_3_count |  | ------------ | ------------ | ------------ | ------------ |  | 9            | 6            | 3            | 2            |  

But I don't want to repeat that for N number of weeks.

Please suggest of I can do it to get desired output

https://stackoverflow.com/questions/65589629/how-to-perform-sql-group-by-week-and-count-of-users-who-are-created-the-week January 06, 2021 at 11:01AM

没有评论:

发表评论