Один из вариантов - использовать CTE для генерации месячных итогов за каждый год, а затем запросить этот CTE, чтобы найти сумму по месяцам.
WITH cte AS (
SELECT
YEAR(db.org.DateCreated) [Year],
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 1 THEN 1 END) Jan,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 2 THEN 1 END) Feb,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 3 THEN 1 END) Mar,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 4 THEN 1 END) Apr,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 5 THEN 1 END) May,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 6 THEN 1 END) Jun,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 7 THEN 1 END) Jul,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 8 THEN 1 END) Aug,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 9 THEN 1 END) Sep,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 10 THEN 1 END) Oct,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 11 THEN 1 END) Nov,
COUNT(CASE WHEN MONTH(db.org.DateCreated) = 12 THEN 1 END) Dec
WHERE YEAR(GETDATE()) - YEAR(db.org.DateCreated) BETWEEN 0 AND 7
FROM yourTable
GROUP BY
YEAR(db.org.DateCreated)
)
SELECT
Year,
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec,
(Jan + Feb + Mar + Apr + May + Jun + Jul + Aug + Sep + Oct + Nov + Dec) AS total
FROM cte
ORDER BY
year;
Обратите внимание, что я заменил ваши звонки на SUM
на COUNT
, что немного более кратко и легко читается.