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
これはより効率的です。エンジンは、存在する場合、日付のインデックスを使用できます。
編集
このトリックを明確にしたいと思います。これは、日付指向のDBで常に必要とされるヘルパー関数です。
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