suppose the fiscal year is starting from July/1st to June/30th.
I have to calculate the week no. accordingly in SQL Server 2005.
Please Suggest!
Many Tha
Try this and use variable @dt for your own needs:
DECLARE @dt DATETIME = GETDATE()
SELECT WeekOfMonth = DATEPART(wk, @dt) - DATEPART(wk,DATEADD(m, DATEDIFF(M, 0, @dt), 0)) + 1
EDITED: My fault as I incorrectly understood the question, my solution returns the week of the month, not of the year.
Using part of @Dems answer and changing mine here is a full working test that outputs 3 columns WeekOfMonth, WeekOfYear and WeekOfFIscalYear based on date and begining of fiscal year available on a temporary table. But I guess the begining of a fiscal year will be always the same for a particular company. I just added different dates and years for testing.
DECLARE @TT TABLE (auxVal INT,
auxdate DATETIME,
fiscal_year DATETIME
)
INSERT @TT
SELECT 100,'19120101 00:00:00','19120701' UNION ALL
SELECT 200,'18120615 00:00:00','18110701' UNION ALL
SELECT 100,'20121121 00:00:00','20120701' UNION ALL
SELECT 200,'20120101 00:00:00','20110701' UNION ALL
SELECT 100,'20150802 00:00:00','20140701' UNION ALL
SELECT 200,'20120330 00:00:00','20110701' UNION ALL
SELECT 322,'20110228 00:00:00','20100701'
SELECT DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, auxDate), 0), auxDate) + 1 WeekOfMonth,
DATEPART( wk, auxDate) WeekOfYear,
DATEDIFF(DAY, (DATEADD(YEAR, DATEDIFF(YEAR, fiscal_year, DATEADD(MONTH, -7, auxDate)), fiscal_year)), auxDate) / 7 + 1 WeekOfFiscalYear
FROM @TT
Result:
WeekOfMonth WeekOfYear WeekOfFiscalYear
-------------------------------------------
1 1 27
3 25 51
4 47 21
1 1 27
2 32 5
5 13 40
5 10 35
-------------------------------------------