DECLARE @FirstDayOfMonth datetime, @LastDayOfMonth datetime
--You can create scalar functions dbo.GetFirstDayOfMonth and dbo.GetLastDayOfMonth
-- try this from December 2012
SELECT @FirstDayOfMonth = '20121201', @LastDayOfMonth = '20121231'
SELECT Disposition, COUNT(Disposition) AS Count
FROM CSLogs.dbo.Logs
WHERE Date BETWEEN @FirstDayOfMonth AND @LastDayOfMonth
GROUP BY Disposition
这样效率更高,引擎可以在 Date 上使用索引(如果存在)。
编辑
我想澄清这个技巧。这是面向日期的数据库中始终需要的辅助函数。
IF(OBJECT_ID('dbo.ufn_FisrtDayOfMonth') IS NOT NULL)
DROP FUNCTION dbo.ufn_FisrtDayOfMonth
GO
CREATE FUNCTION dbo.ufn_FisrtDayOfMonth(@DATE DATE)
RETURNS DATETIME
BEGIN
RETURN CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, @DATE) as DATETIME)
END
GO
IF(OBJECT_ID('dbo.ufn_FisrtDayOfNextMonth') IS NOT NULL)
DROP FUNCTION dbo.ufn_FisrtDayOfNextMonth
GO
CREATE FUNCTION dbo.ufn_FisrtDayOfNextMonth(@DATE DATE)
RETURNS DATETIME
BEGIN
RETURN CAST(DATEADD(d, - DATEPART(d, @DATE) + 1, DATEADD(m, 1, @DATE)) as DATETIME)
END
GO
现在你可以试试这个:
DECLARE @FirstDayOfMonth datetime, @FirstDayOfNextMonth datetime
SELECT @FirstDayOfMonth = dbo.ufn_FisrtDayOfMonth(GETDATE()), @FirstDayOfNextMonth = dbo.ufn_FisrtDayOfNextMonth(GETDATE())
SELECT Disposition, COUNT(Disposition) AS Count
FROM CSLogs.dbo.Logs
WHERE Date >= @FirstDayOfMonth
AND Date < @FirstDayOfNextMonth
GROUP BY Disposition