If you have a numbers table or a calendar table of some sort, that will make it much easier to do this. If you don't have a calendar table, you can construct one like this:CREATE TABLE #tmpDates([date] DATETIME NOT NULL PRIMARY KEY CLUSTERED);DECLARE @startDate DATETIME; SET @startDate = '20110501';DECLARE @Days INT; SET @days = 100;WITH N(n) AS ( SELECT 1 UNION ALL SELECT n+1 FROM N WHERE n < @Days)INSERT INTO #tmpDates SELECT DATEADD(dd,n-1,@startDate) FROM N;
Once you have the Calendar table like above, your query would be something like this. If you have a table where the wells are listed, it would have been a little easier - we could avoid the WellsCTE which is trying to find all the wells we are interested in.WITH WellsCTE AS( SELECT DISTINCT well_id FROM WellsTable )SELECT wc.well_id, d.[Date], ISNULL(w.OFF_WELL,0) AS OFF_WELLFROM WellsCTE wc CROSS JOIN #tmpDates d LEFT JOIN WellsTable w ON wc.well_id = w.well_id AND d.[Date] = w.OFF_WELL_DATEORDER BY wc.well_id, d.[Date]