SQL Script - Categorising event data by the date they occured

WalmZ 21 Reputation points
2022-01-07T09:00:05.157+00:00

Hi, I am relatively new to writing SQL scripts, I was wondering if anybody could help with this? I have an formula that I am applying to a SQL extract in Excel which essentially groups each event by the date that it happened. Id like to make this smarter and develop this into my SQL so this calculation is done before extracting.

I am only interested in events that have taken place in the last year as of today. So it doesnt work to group them by calendar month, as today may fall mid month, therefore the formula just looks back and groups by 'Month 1", "Month 2" etc. The formula is looking back over a 12 month period... "1" being those events in the first month of the year, "12" being events in the last month etc and anything prior to a year back is "Historical".

I have been advised by a colleague that a CASE WHEN statement may work in SQL for this but I am struggling to work out how to replicate this.
Any advice, I would be very grateful. See below for my workings in Excel.

163088-formula-screenshot.png

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,769 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 117K Reputation points
    2022-01-07T09:25:05.733+00:00

    If you need just the Month column from EVENT_DATE, then try this approach:

    select EVENT_DATE, EVENT_DATA, COMBINED_EVENT_KEY,
        case 
            when EVENT_DATE < dateadd(month, -12, getdate()) then 'HISTORICAL'
            when EVENT_DATE < dateadd(month, -11, getdate()) then '1'
            when EVENT_DATE < dateadd(month, -10, getdate()) then '2'
            when EVENT_DATE < dateadd(month, -9, getdate()) then '3'
            when EVENT_DATE < dateadd(month, -8, getdate()) then '4'
            when EVENT_DATE < dateadd(month, -7, getdate()) then '5'
            when EVENT_DATE < dateadd(month, -6, getdate()) then '6'
            when EVENT_DATE < dateadd(month, -5, getdate()) then '7'
            when EVENT_DATE < dateadd(month, -4, getdate()) then '8'
            when EVENT_DATE < dateadd(month, -3, getdate()) then '9'
            when EVENT_DATE < dateadd(month, -2, getdate()) then '10'
            when EVENT_DATE < dateadd(month, -1, getdate()) then '11'
            else '12'
        end as Month
    from MyTable
    

    Show other details if you need something more.


0 additional answers

Sort by: Most helpful

Your answer

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