Решение (чистый SQL):
SELECT right(convert(varchar, tbl.[Date], 106), 8) [Date],
(SELECT COUNT(*) FROM [Table1] t1 WHERE month(t1.[Date]) = (tbl.m - 1) AND year(t1.[Date])=tbl.y) [Begin],
(SELECT COUNT(*)
FROM Table1 t1
WHERE month(t1.[Date]) = tbl.m
AND year(t1.[Date])=tbl.y
AND t1.InventoryID NOT IN (
SELECT InventoryID
FROM Table1
WHERE month(t1.[Date]) = month(DATEADD(month, 1, [Date])) AND year(t1.[Date]) = year([Date]))) [Added],
(SELECT COUNT(*)
FROM Table1 t1
WHERE month(t1.[Date]) = (tbl.m - 1)
AND year(t1.[Date])=tbl.y
AND t1.InventoryID NOT IN (
SELECT InventoryID
FROM Table1
WHERE month([Date]) = month(DATEADD(month, 1, t1.[Date])) AND year(t1.[Date]) = year([Date]))) [Removed],
(SELECT COUNT(*) FROM [Table1] t1 WHERE month(t1.[Date]) = (tbl.m) AND year(t1.[Date])=tbl.y) [End]
FROM (SELECT DISTINCT [Date], month([Date]) [m], year([Date]) [y] from Table1) as tbl
Воспроизведение:
Пример сценария данных:
SELECT * INTO Table1 FROM (
SELECT GETDATE() [Date], '1111-111A' [InventoryID], 60 [InventoryValue] UNION
SELECT GETDATE() [Date], '1111-111B' [InventoryID], 50 [InventoryValue] UNION
SELECT GETDATE() [Date], '1111-111C' [InventoryID], 30 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111B' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111C' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 1, GETDATE()) [Date], '1111-111D' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111B' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111C' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111D' [InventoryID], 40 [InventoryValue] UNION
SELECT DATEADD(month, 2, GETDATE()) [Date], '1111-111F' [InventoryID], 40 [InventoryValue]) as tbl
Вывод:
Date Begin Added Removed End
---------------------------------------
Feb 2012 0 3 0 3
Mar 2012 3 1 1 3
Apr 2012 3 1 0 4