Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a category column based on date

I am trying to create a column called cycle grouping which will categorize based on created_at_date column, starting 9/11. I want to categorize first 14 days as first cycle and next 14 days as second cycle, and then reset it. For example:

| created_at_date | cycle_grouping (want to create this)  |
| :--------------:| :------------------------------------:|
|  09/11/2022     | 09/11/2022First Cycle                 |
|  09/18/2022     | 09/18/2022First Cycle                 |
|  09/25/2022     | 09/25/2022Second Cycle                |
|  10/02/2022     | 10/02/2022Second Cycle                |
|  10/09/2022     | 10/09/2022First Cycle                 |
|  10/16/2022     | 10/16/2022First Cycle                 |
|  10/23/2022     | 10/23/2022Second Cycle                |
|  10/30/2022     | 10/30/2022Second Cycle                |
...... continue this for other weeks 

Any ideas will be really appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can get the difference in days between 9/11/2022 and created_at_date, take the remainder after dividing by 28, and seeing if that is < 14 or not.

select created_at_date,
  case when DATEDIFF(day, '9/11/2022', created_at_date) % 28 < 14 then 'First Cycle' else 'Second Cycle' end as cycle_grouping
from mytable

Note: It’s <14 instead of <=14 because the first cycle goes from days 0 – 13 and the next from days 14 – 27. Day 28 starts first cycle again. You’ll have to tweak slightly if that’s not exactly what you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading