вот так:
DECLARE @year INT,
@i INT = 1,
@date VARCHAR(6),
@month INT = 1,
@months INT = 12,
@sql NVARCHAR(MAX)
DECLARE @years TABLE (
Id INT IDENTITY,
myYear INT
)
INSERT INTO @years (myYear)
VALUES (2016),
(2017),
(2018)
CREATE TABLE #table (
field1 [your data type],
field2 [your data type],
field3 [your data type],
myDate VARCHAR(6),
myCount INT
)
WHILE @i <= (SELECT MAX(Id) FROM @years)
BEGIN
SELECT @year = myYear
FROM @years
WHERE Id = @i
WHILE @month <= @months
BEGIN
IF @month < 10
SET @date = @year + '0' + CAST(@month as VARCHAR(2))
ELSE
SET @date = @year + CAST(@month as VARCHAR(2))
SET @sql = 'INSERT INTO #table SELECT field1 ,field2 ,field3, year_month as myDate, count(distinct(table1.field4)) as myCount
FROM table1 JOIN table2 ON table1.field4 = table2.field4
WHERE year_month = ''' + CAST(@date AS NVARCHAR(MAX)) + ''' GROUP BY field1, field2, field3, year_month ORDER BY year_month, field1, field2, field3'
EXECUTE sp_executesql @sql
SET @month = @month + 1
END
SET @month = 1
SET @i = @i + 1
END
SELECT * FROM #table
DROP TABLE #table