Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL calculated column how to get ISO week number [duplicate]

I have this Calendar table (code below) based on the Date and then Calculated columns. The problem is that it returns me 53rd weeks because of the logic 52 * 7 = 364 so actually we always get some "spare" days per year, as happens for example in 2014 for these days:

2014-12-28
2014-12-29
2014-12-30
2014-12-31

In the company I work, we must use ISO calendar weeks. How do I change this table in order to get the ISO calendar weeks instead of this?

I forgot to mention that I use: SQL Server 2008 R2 and 2012.

CREATE TABLE [dbo].[TO_BDB_NOSSCE_CALENDAR](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [DATE] [date] NOT NULL,
    [YEAR]  AS (datepart(year,[DATE])) PERSISTED,
    [SEMESTER]  AS (case when datepart(month,[DATE])<(7) then '1' else '2' end) PERSISTED NOT NULL,
    [TRIMESTER]  AS (case when datepart(month,[DATE])<(4) then '1' else case when datepart(month,[DATE])<(7) then '2' else case when datepart(month,[DATE])<(10) then '3' else '4' end end end) PERSISTED NOT NULL,
    [MONTH]  AS (case when len(CONVERT([varchar](2),datepart(month,[DATE]),0))=(1) then '0'+CONVERT([varchar](2),datepart(month,[DATE]),0) else CONVERT([varchar](2),datepart(month,[DATE]),0) end) PERSISTED,
    [WEEK]  AS (case when len(CONVERT([varchar](2),datepart(week,[DATE]),0))=(1) then '0'+CONVERT([varchar](2),datepart(week,[DATE]),0) else CONVERT([varchar](2),datepart(week,[DATE]),0) end),
    [DAY]  AS (case when len(CONVERT([varchar](2),datepart(day,[DATE]),0))=(1) then '0'+CONVERT([varchar](2),datepart(day,[DATE]),0) else CONVERT([varchar](2),datepart(day,[DATE]),0) end) PERSISTED,
    [WEEKNUMBER]  AS (datepart(week,[DATE])),
PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO
like image 706
KathyBlue Avatar asked Aug 31 '25 06:08

KathyBlue


1 Answers

In SQL Server 2008+, you can use the following:

SELECT DATEPART(ISO_WEEK, <DATE>)

The following SO question discusses other methods to derive the ISO week:

Isoweek in SQL Server 2005

like image 65
SQLDiver Avatar answered Sep 02 '25 19:09

SQLDiver