2

我想对处置进行计数,并且只计算当月的处置,这是我拥有的代码:

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 并且没有显示日期列。

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

4

1 回答 1

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 

这样效率更高,引擎可以在 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 
于 2012-12-13T14:20:44.983 回答