Away from the beautiful and probably a lot left for optimization, but it is tested and works with SQL Server.
Be sure to replace all @Table links with the actual tab name.
DECLARE @Table TABLE (ID INTEGER, LoginDate DATETIME, RemovalDate DATETIME)
INSERT INTO @Table
SELECT 1, '2009/08/01', NULL
UNION ALL SELECT 2, '2009/09/12', '2010/01/02'
UNION ALL SELECT 3, '2009/08/31', '2009/10/29'
UNION ALL SELECT 4, '2010/02/17', NULL
UNION ALL SELECT 5, '2009/10/18', '2009/11/22'
SELECT CAST(ld.yr AS VARCHAR(4)) + '/' + RIGHT('0' + CAST(ld.mnth AS VARCHAR(2)), 2), ld.RunningTotal - ISNULL(rd.RunningTotal, 0)
FROM (
SELECT yr, mnth, RunningTotal = MAX(RunningTotal)
FROM (
SELECT yr = YEAR(t1.LoginDate), mnth = MONTH(t1.LoginDate), RunningTotal = COUNT(*)
FROM @Table t1
CROSS JOIN @Table t2
WHERE t1.LoginDate >= t2.LoginDate
GROUP BY t1.LoginDate
) ld
GROUP BY ld.yr, ld.mnth
) ld
LEFT OUTER JOIN (
SELECT yr, mnth, RunningTotal = MAX(RunningTotal)
FROM (
SELECT yr = YEAR(t1.RemovalDate), mnth = MONTH(t1.RemovalDate), RunningTotal = COUNT(*)
FROM @Table t1
CROSS JOIN @Table t2
WHERE t1.RemovalDate >= t2.RemovalDate
GROUP BY t1.RemovalDate
) ld
GROUP BY ld.yr, ld.mnth
) rd ON rd.yr <= ld.yr AND rd.mnth <= ld.mnth
ORDER BY
1, 2
source
share