Skip to content
Advertisement

Get All dates for given month and year and join in same table sql

Currently I have data in below format in my table

enter image description here

How can I get date wise for every month and year like below

enter image description here

Advertisement

Answer

First, personally, I would create a Calendar Table. You can quickly create a simple one with the below:

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 indexes
ALTER TABLE dbo.CalendarTable ADD CONSTRAINT PK_CalendarDate PRIMARY KEY CLUSTERED (CalendarDate);
GO

CREATE INDEX IX_YearMonthDay ON dbo.CalendarTable (CalenderYear,CalenderMonth,CalenderDay);

GO
WITH 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.CalendarTable
SELECT 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 WHCNC
FROM dbo.YourTable YT
     JOIN dbo.CalendarTable CT ON YT.PlanYear = CT.CalenderYear
                              AND YT.PlanMonth = CT.CalenderMonth;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement