从基于StartDate和endDate的表中获取每月数据

时间:2016-07-05 21:06:34

标签: sql-server

我有一个包含详细信息(状态,ID,标题等)的主表以及开始日期和结束日期。当月要求每月有效的详细信息。

我做了类似这样的事情,这给了我一个月的明智记录但不考虑一年。当表行增加时,此代码太慢。请帮帮我。

DECLARE @LoopCounter INT,
        @Max INT, 
        @MonthName NVARCHAR(100),
        @TransStatus int,
        @Year int
BEGIN
    SELECT @LoopCounter = min(id), @Max = max(Id) 
    FROM TableName

    CREATE TABLE #Active 
    (
        Id INT IDENTITY(1,1),
        Month varchar(30)
    )

    WHILE (@LoopCounter <= @Max)
    BEGIN
        INSERT into #Active
            SELECT DateName(MONTH, DATEADD(MONTH, nos.monthnos, (Select StartDate from TableName where id=@LoopCounter And Year(StartDate)=@Year)-1 ) )
            FROM (SELECT 1 monthnos
                    UNION SELECT 2
                    UNION SELECT 3
                    UNION SELECT 4
                    UNION SELECT 5
                    UNION SELECT 6
                    UNION SELECT 7
                    UNION SELECT 8
                    UNION SELECT 9
                    UNION SELECT 10
                    UNION SELECT 11
                    UNION SELECT 12) nos 
            WHERE nos.monthnos <= DATEDIFF(MONTH, (Select StartDate from TableName where id=@LoopCounter),
                                                  (Select EndDate from TableName where id=@LoopCounter)+1 )
        SET @LoopCounter = @LoopCounter + 1
    END
END

SELECT COUNT(*) As ActiveCount, Month 
FROM #Active 
GROUP BY Month

1 个答案:

答案 0 :(得分:1)

您的问题有点令人困惑,但基于&#34;需要当月的活跃详细信息&#34;我觉得这样的事情对你来说要快得多。

    SELECT COUNT(*), YEAR([Start Date]), Month([Start Date])
    FROM MasterTable
    WHERE [Start Date] BETWEEN DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) AND GETDATE()
    GROUP BY 
    YEAR([Start Date]), Month([Start Date])