Currently I have data in below format in my table
How can I get date wise for every month and year like below
Advertisement
Answer
First, personally, I would create a Calendar Table. You can quickly create a simple one with the below:
x
CREATE TABLE [dbo].[CalendarTable] ([CalendarDate] [date] NOT NULL, [CalenderYear] AS (DATEPART(YEAR, [CalendarDate])) PERSISTED, [CalenderMonth] AS (DATEPART(MONTH, [CalendarDate])) PERSISTED, [CalenderDay] AS (DATEPART(DAY, [CalendarDate])) PERSISTED, [CalenderMonthName] AS (DATENAME(MONTH, [CalendarDate])), [JulianDate] AS ((DATEPART(YEAR, [CalendarDate]) * (1000) + DATEDIFF(DAY, DATEFROMPARTS(DATEPART(YEAR, [CalendarDate]), (1), (1)), [CalendarDate])) + (1)) PERSISTED);GO--Create a couple indexesALTER TABLE dbo.CalendarTable ADD CONSTRAINT PK_CalendarDate PRIMARY KEY CLUSTERED (CalendarDate);GOCREATE INDEX IX_YearMonthDay ON dbo.CalendarTable (CalenderYear,CalenderMonth,CalenderDay);GOWITH N AS( SELECT N FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),Tally AS( SELECT TOP (SELECT DATEDIFF(DAY,'19000101','21000101')) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I FROM N N1, N N2, N N3, N N4, N N5)INSERT INTO dbo.CalendarTableSELECT DATEADD(DAY, T.I, '19000101')FROM Tally T;Then is just a trivial case of joining your table to the calendar table:
SELECT YT.PlanYear, YT.PlanMonth, CT.CalendarDate, 1 AS WHTAP, 1 AS WHCNCFROM dbo.YourTable YT JOIN dbo.CalendarTable CT ON YT.PlanYear = CT.CalenderYear AND YT.PlanMonth = CT.CalenderMonth;
