Share via

Date categorization

readytolearn 1 Reputation point
2022-02-03T19:35:26.117+00:00

I have a date in SQL (assuming 01/15/2021). I need to be able to categorize this date as past 30\past60\past365. What would be the best way to do it?
So my result set should show which category this date falls under. I can have 3 different columns that say past 30 or past 60 and say Y or N for this date. But I need one column that I can use for the categorization. This date will fall under past 30 and past 60 days.
How do I categorize it?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


1 answer

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2022-02-03T22:13:15.797+00:00

    I think that you can use something like this:

    select *,
        case
            when days <= 30 then 'past 30'
            when days <= 60 then 'past 60'
            when days <= 365 then 'past 365'
        end as Category
    from MyTable
    cross apply (values (datediff(day, MyDateColumn, GETDATE()))) t(days)
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.