为什么不同的日期数学运算产生相同的值?

时间:2016-01-13 21:44:05

标签: sql-server tsql date-math

我可以添加六天的日期并获得我期望的结果,但如果我在同一天添加七天,我会得到相同的日期。

我的意思是这个;当用户输入“ 12/27/2015 ”作为@BegDate参数的值时,此声明:

DECLARE 
@Week1End datetime = DATEADD(Day, 6, @BegDate),
@Week2Begin datetime = DATEADD(Day, 7, @BegDate);

...导致@ Week1End和@ Week2Begin都是同一个日期(2016-01-02),正如您从返回的结果集中看到的那样:

enter image description here

这是TSQL:

CREATE PROCEDURE [dbo].[variancePriceByProductWithPriceChangePercentage]
    @Unit varchar(25),
    @BegDate datetime,
    @EndDate datetime
AS

DECLARE 
@Week1End datetime = DATEADD(Day, 6, @BegDate),
@Week2Begin datetime = DATEADD(Day, 7, @BegDate);

Select Ind.Description,
    @BegDate  BegDate,
    @Week1End Week1End,
    @Week1End Week2Begin,
    @EndDate EndDate,
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.QtyShipped ELSE 0 END) 
Week1Usage,
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 END) 
Week2Usage,
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) 
Week1Price,
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.Price ELSE 0 END) -
   SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.QtyShipped ELSE 0 END) 
UsageVariance,
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 END) 
-
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) 
PriceVariance,
    (SUM(CASE WHEN Ind.InvoiceDate BETWEEN @Week2Begin AND @EndDate THEN Ind.QtyShipped ELSE 0 
END)  -
    SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END) )
    / 
NULLIF(SUM(CASE WHEN Ind.InvoiceDate BETWEEN @BegDate AND @Week1End THEN Ind.Price ELSE 0 END),0) 
PercentageOfPriceVariance
    From    InvoiceDetail Ind
    Where   Ind.Unit = @Unit
    AND Ind.InvoiceDate BETWEEN @BegDate AND @EndDate
    Group By Ind.Description

那么为什么 @BegDate + 6 等同于 @BegDate + 7

2 个答案:

答案 0 :(得分:2)

@Week1End Week1End,
@Week1End Week2Begin,

再看看这段代码......

答案 1 :(得分:1)

您确定:

DECLARE @BegDate datetime = GETDATE()

SELECT @BegDate, DATEADD(Day, 6, @BegDate), DATEADD(Day, 7, @BegDate);

结果:

enter image description here

我认为你的问题在这里:

@Week1End Week1End,
@Week1End Week2Begin, ---<<<<<--- 

应该是:

@Week1End Week1End,
@Week2BeginWeek2Begin, ---<<<<<---