试试这个——
SELECT
totalDept = count(dept)
, gr.grouped_by_dept
FROM employee
CROSS JOIN (
SELECT grouped_by_dept = count(1)
FROM employee
GROUP BY dept
) gr
WHERE datepart (MM, joindate) = datepart (MM, dateadd(MM, -1, getdate()))
AND datepart (YYYY, joindate) = datepart (YYYY, dateadd(MM, -1, getdate()))
GROUP BY datename (MONTH, joindate) + ' , ' + datename (YEAR, joindate)
更新:
DECLARE @FirstDayOfMonth DATETIME
SELECT @FirstDayOfMonth = DATEADD(DAY, -(DAY(GETDATE()) - 1), GETDATE())
SELECT
t2.MONTHYEAR
, t2.[system]
, t3.[countBySystem]
, NewAddr = COUNT(t2.[address])
FROM (
SELECT
MONTHYEAR = DATENAME(MONTH, DateInserted) + ' , ' + DATENAME(YEAR, DateInserted)
, t.[system]
, t.[address]
FROM dbo.testtable t
WHERE DATEADD(DAY, -(DAY(t.DateInserted) - 1), t.DateInserted) = @FirstDayOfMonth
) t2
JOIN (
SELECT
t2.[system]
, [countBySystem] = COUNT(1)
FROM dbo.testTable t2
GROUP BY t2.[system]
) t3 ON t2.[system] = t3.[system]
GROUP BY
t2.MONTHYEAR
, t2.[system]
ORDER BY NewAddr