Skip to content
Advertisement

How to create your own week intervals

Objective:

I have a 49 dates in my data set and I would like to group them by weeks in order ASC without using the WEEK or ISO_WEEK functions.

The output should look like this:

+------------+------+
|   dates    | week |
+------------+------+
| 2019-04-05 |    1 |
| 2019-04-06 |    1 |
| 2019-04-07 |    1 |
| 2019-04-08 |    1 |
| 2019-04-09 |    1 |
| 2019-04-10 |    1 |
| 2019-04-11 |    1 |
| 2019-04-12 |    2 |
| 2019-04-13 |    2 |
+------------+------+

Is there a better way than using a case statement coupled with a row_number() such as this:

case when rn <= 7 then w1 when rn >7 and <= 14 then w2 ....

Advertisement

Answer

You could use arithmetic:

(row_number() over (order by dates) + 6) / 7
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement