我的表名为company,其列为公司名称,创建日期等。
我想了解本月创建的公司数量。
我有每周智能计数的存储过程
CREATE PROCEDURE [dbo].[pr_NewCmpCount]
@StartDate DATETIME = NULL --'20130508'
, @EndDate DATETIME = NULL --'20130515'
AS
BEGIN
DECLARE @DateDiff INT
, @MainDate DATETIME
IF @StartDate IS NULL AND @EndDate IS NULL
BEGIN
IF (DATEPART(dw,GETDATE()) > 3)
SET @DateDiff = 0
ELSE
SET @DateDiff = 6
SET @MainDate = DATEADD (MINUTE, -30, DATEADD (HOUR, -5, DATEADD(wk, DATEDIFF(wk,@DateDiff,GETDATE()), 0)))
SELECT @StartDate = DATEADD (MINUTE, -30, DATEADD (HOUR, -5, DATEADD(wk, DATEDIFF(wk,0,@MainDate), -5)))
SELECT @EndDate = DATEADD (MINUTE, -30, DATEADD (HOUR, -5, DATEADD(wk, DATEDIFF(wk,0,@MainDate), 2)))
SELECT CONVERT (VARCHAR, Count(*)) AS [Count]
, CONVERT (DATE, DATEADD (DD, 1, @StartDate)) AS [StartDate]
, CONVERT (DATE, @EndDate) AS [EndDate]
FROM
Company WITH(NOLOCK)
WHERE CreateDate >= @StartDate
AND CreateDate < @EndDate
END
ELSE
IF ((CONVERT (DATE, @StartDate) < CONVERT (DATE, @EndDate)) AND (CONVERT (DATE, @EndDate) < CONVERT (DATE, GETDATE())))
BEGIN
SET @StartDate = CONVERT (DATE, @StartDate)
SET @EndDate = CONVERT (DATE, @EndDate)
SELECT @StartDate = DATEADD (MINUTE, -30, DATEADD (HOUR, -5, @StartDate))
SELECT @EndDate = DATEADD (MINUTE, 30, DATEADD (HOUR, 18, @EndDate))
SELECT CONVERT (VARCHAR, Count(*)) AS [Count]
, CONVERT (DATE, DATEADD (DD, 1, @StartDate)) AS [StartDate]
, CONVERT (DATE, @EndDate) AS [EndDate]
FROM
Company WITH(NOLOCK)
WHERE CreateDate >= @StartDate
AND CreateDate < @EndDate
END
ELSE
SELECT 'Please Run After Tuesday of Every Week or Given the Valid Date' [Count]
, CONVERT (DATE, @StartDate) AS [StartDate]
, CONVERT (DATE, @EndDate) AS [EndDate]
END
此存储过程的输出是
Count Startdate EndDate 10 2016-03-13 2016-03-22
预期产出
Count Startdate EndDate 20 2016-02-01 2016-02-29
我需要在存储过程中修改哪些内容才能获得按月计算?
答案 0 :(得分:0)
这样的事情:
DECLARE @StartDt Date
DECLARE @EndDt date
SELECT @StartDt,@EndDt,Count(*) AS TotalCompanies FROM company
WHERE [create date] BETWEEN @StartDt AND @EndDt
为简单起见,我跳过了存储过程格式。