SQL Query用于提取当月的数据

时间:2012-12-13 14:16:47

标签: sql sql-server

我想要对这些处置进行统计,只计算当月的那些,这是我的代码:

SELECT        Disposition, COUNT(Disposition) AS Count, Date
FROM            CSLogs.dbo.Logs
GROUP BY Disposition, Date
HAVING        (DATEPART(month, GETDATE()) = DATEPART(month, Date)) AND (DATEPART(year, GETDATE()) = DATEPART(year, Date))

但我得到的结果是:

Disposition Count   Date
LOC         1       2012-12-10
Save        3       2012-12-11
LOC         1       2012-12-12
Sale        1       2012-12-12
Save        3       2012-12-12

正如你所看到我有重复,但我不是在寻找,我正在寻找例如,LOC在计数下是2并且没有显示日期列。

希望我已经提供了足够的信息并提前致谢!

1 个答案:

答案 0 :(得分:3)

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