Вот пример, который будет выполнять подзапрос для каждого столбца.
SELECT RIGHT('0' + CAST(allDates.EventMonth AS CHAR(2)), 2) + '-' + CAST(allDates.EventYear AS CHAR(4)) AS [Month-Year],
(SELECT COUNT(1) FROM EventTable WHERE DATEPART(YEAR, Date_Event1) = allDates.EventYear AND DATEPART(MONTH, Date_Event1) = allDates.EventMonth) AS Date_Event1,
(SELECT COUNT(1) FROM EventTable WHERE DATEPART(YEAR, Date_Event2) = allDates.EventYear AND DATEPART(MONTH, Date_Event2) = allDates.EventMonth) AS Date_Event2,
(SELECT COUNT(1) FROM EventTable WHERE DATEPART(YEAR, Date_Event3) = allDates.EventYear AND DATEPART(MONTH, Date_Event3) = allDates.EventMonth) AS Date_Event3,
(SELECT COUNT(1) FROM EventTable WHERE DATEPART(YEAR, Date_Event4) = allDates.EventYear AND DATEPART(MONTH, Date_Event4) = allDates.EventMonth) AS Date_Event4
FROM (
SELECT EventYear, EventMonth
FROM (
SELECT DATEPART(YEAR, Date_Event1) AS EventYear, DATEPART(MONTH, Date_Event1) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event2) AS EventYear, DATEPART(MONTH, Date_Event2) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event3) AS EventYear, DATEPART(MONTH, Date_Event3) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event4) AS EventYear, DATEPART(MONTH, Date_Event4) AS EventMonth
FROM EventTable
) AS allDates
GROUP BY EventYear, EventMonth
) AS allDates
ORDER BY allDates.EventYear, allDates.EventMonth
В этом примере используется INNER JOIN, но он может работать лучше в зависимости от размеров таблицы и индексов. et c.
SELECT RIGHT('0' + CAST(allDates.EventMonth AS CHAR(2)), 2) + '-' + CAST(allDates.EventYear AS CHAR(4)) AS [Month-Year],
SUM(IIF(DATEPART(YEAR, e.Date_Event1) = allDates.EventYear AND DATEPART(MONTH, e.Date_Event1) = allDates.EventMonth, 1, 0)) AS Date_Event1,
SUM(IIF(DATEPART(YEAR, e.Date_Event2) = allDates.EventYear AND DATEPART(MONTH, e.Date_Event2) = allDates.EventMonth, 1, 0)) AS Date_Event2,
SUM(IIF(DATEPART(YEAR, e.Date_Event3) = allDates.EventYear AND DATEPART(MONTH, e.Date_Event3) = allDates.EventMonth, 1, 0)) AS Date_Event3,
SUM(IIF(DATEPART(YEAR, e.Date_Event4) = allDates.EventYear AND DATEPART(MONTH, e.Date_Event4) = allDates.EventMonth, 1, 0)) AS Date_Event4,
FROM (
SELECT EventYear, EventMonth
FROM (
SELECT DATEPART(YEAR, Date_Event1) AS EventYear, DATEPART(MONTH, Date_Event1) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event2) AS EventYear, DATEPART(MONTH, Date_Event2) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event3) AS EventYear, DATEPART(MONTH, Date_Event3) AS EventMonth
FROM EventTable
UNION ALL
SELECT DATEPART(YEAR, Date_Event4) AS EventYear, DATEPART(MONTH, Date_Event4) AS EventMonth
FROM EventTable
) AS allDates
GROUP BY EventYear, EventMonth
) AS allDates
INNER JOIN EventTable AS e ON 1 = 1
GROUP BY allDates.EventYear, allDates.EventMonth
ORDER BY allDates.EventYear, allDates.EventMonth