0

我有一个存储过程,它遍历财政年度的几个月,并对每个月的项目进行计数。我知道事实上有 176 个项目,但是当我运行它时,它返回的总计数为 182。我尝试从 @EndDate 中删除一秒,但我的总计数为 165。所以我要么计算项目两次,要么不算全部。谁能帮助我在这里做错了什么?以下是我正在做的精简版:

DECLARE @Date DATETIME
DECLARE @EndDate DATETIME

SELECT @Date = CAST((@Year - 1) as VARCHAR) + '-07-01'
SELECT @EndDate = DATEADD(Month, 1, @Date)


DECLARE @Count INT
SELECT @Count = 0
WHILE @Count < 12

BEGIN

    SELECT 
        COUNT(yai.ID)
    FROM
        table_1    yai 
        INNER JOIN table_2 yat ON yai.ID = yat.ID 
    WHERE
        (yat.Date_Received BETWEEN CONVERT(VARCHAR, @Date, 101) AND CONVERT(VARCHAR, @EndDate, 101))  AND 
        yai.Pro_Type = @Value AND yat.Type = 'PC'

    SELECT @Count = @Count + 1
    SELECT @Date = DATEADD(MONTH, 1, @Date)
    SELECT @EndDate = DATEADD(MONTH, 1, @EndDate)

END
4

7 回答 7

1

介于两者之间,因此您的 1 秒减法应该存在(甚至是一天)。我的猜测是有些 yais 没有相应的 yat。

编辑:您的代码是伪造的。除了与格式 101 相等之外,您不能进行比较。

于 2009-09-22T17:54:25.017 回答
0

从我的头顶。

SELECT DATEPART(month, yat.Date) as month, COUNT(yai.ID)
FROM table_1 yai 
INNER JOIN table_2 yat ON yai.ID = yat.ID 
WHERE
    yai.Pro_Type = @Value AND yat.Type = 'PC' 
    AND DATEPART(year, yat.Date)=@Year
GROUP BY DATEPART(month, yat.Date)
ORDER BY DATEPART(month, yat.Date)
于 2009-09-22T17:56:25.763 回答
0

我曾经说过一些有趣的话,比如我知道有 50 个项目,而 sql 返回 60...

我发现我总是错的!:)

尝试从日期和时间字段中剥离时间:

DATEADD(d, DATEDIFF(d, 0, GetDate()), 0)

于 2009-09-22T17:56:32.917 回答
0

你不能这样做吗?以下查询将为您提供按月分组的计数。如果将其放在视图中,则可以从视图中选择并使用 where 子句按您感兴趣的年份和月份进行过滤。

select year(yat.Date_Received) as year, month(yat.Date_Received) as month, count(*) as count
    count(yai.ID)
from table_1 yai 
inner join table_2 yat on yai.ID = yat.ID 
where yai.Pro_Type = 'some_value' 
    and yat.Type = 'PC'
group by year(yat.Date_Received), month(yat.Date_Received)
于 2009-09-22T17:57:21.557 回答
0

这是 SQL 代码中不必要循环的典型案例,但如果您想通过循环解决此问题,请将循环中的选择更改为:

 SELECT 
        COUNT(yai.ID)

到:

 SELECT 
     @Date,@EndDate,*

然后查看输出并检查返回的行

于 2009-09-22T17:59:30.647 回答
0

为什么不将日历月转换为绝对整数引用,如下所示:

DECLARE @BeginDate datetime = '7/1/2008'
DECLARE @EndDate datetime = '6/30/2009'
--
-- Convert calendar months into an absoulte integer:
--
DECLARE @BeginMonth int = (DatePart(year, @BeginDate) * 12) + DatePart(month, @BeginDate)
DECLARE @EndMonth int = (DatePart(year, @EndDate) * 12) + DatePart(month, @EndDate)

SELECT COUNT(yai.ID)
FROM table_1 yai
INNER JOIN table_2 yat ON yai.ID = yat.ID
WHERE (DatePart(year, yat.Date_Received) * 12) + DatePart(month, yat.Date_Received) 
    BETWEEN @BeginMonth AND @EndMonth)
AND yai.Pro_Type = @Value
AND yat.Type = 'PC'
于 2009-09-22T18:05:32.437 回答
0

I found this question because I had troubles with using string date in queries using Between and I was using metadata, my co-worker helped me, so I hope this helps you too:

N'convert(date,[fld_myDate]) Between  convert(date,''01/01/2016'') AND convert(date,''08/26/2017'') '
于 2017-08-26T12:17:48.927 回答