Home > Mobile >  how to change week num to iso week in SQL
how to change week num to iso week in SQL

Time:11-03

I have data that looks like this:

CustomerID Trans_date
C001 01-sep-22
C001 04-sep-22
C001 14-sep-22
C002 03-sep-22
C002 01-sep-22
C002 18-sep-22
C002 20-sep-22
C003 02-sep-22
C003 28-sep-22
C004 08-sep-22
C004 18-sep-22

after processing using this query:

WITH CTE (customerID,FirstWeek,RN) AS (
        SELECT customerID,MIN(DATEPART(week,tp_date)) TransWeek,
        ROW_NUMBER() over(partition by customerID ORDER BY DATEPART(week,tp_date) asc ) FROM all_table
        GROUP BY customerID,DATEPART(week,tp_date)
    ) 
    
    SELECT CTE.customerID, CTE.FirstWeek,  
         (select TOP 1 (DATEPART(week,c.tp_date))   
            from all_table c 
                where c.customerID = CTE.customerID AND DATEPART(week,C.tp_date) > CTE.FirstWeek 
                    )   SecondWeek 
    FROM CTE  
    WHERE RN = 1

the result is like this

CustomerID firstweek secondweek
C001 36 37
C002 36 39
C003 36 40
C004 37 39

but the results will be appropriate when using the weeknum in excel. but what i hope the result is isoweek format which will look like this

CustomerID firstweek secondweek
C001 35 37
C002 35 37
C003 35 39
C003 36 37

CodePudding user response:

Datepart has an isowk parameter. So instead of

DATEPART(week,...

use

DATEPART(isowk,...

CodePudding user response:

Have create a small fiddle to help: db<>fiddle

And as I understand I would just use min and max values of weeks grouped by customer

  • Related