计算同一列中日期之间的差异

时间:2019-05-07 20:38:11

标签: sql-server tsql datediff

我正在尝试计算同一列中的日期之间的差值,但到目前为止没有成功。
这是我正在使用的数据,这是我到目前为止所做的代码。我提供了脚本供您参考。希望它会有所帮助。

CREATE TABLE Test (Product varchar (250), Orderdate Datetime );
insert into TEST (product, orderdate) 
values ('A', '2019/01/01'), ('B', '2019/01/11'),  ('C', '2019/01/15'),  ('D', '2019/01/20');

脚本我正在运行并获得实际结果。

SELECT  t.Product,  t.orderdate,    
        datediff(day,t2.orderdate,t.orderdate) as diffdays  
FROM TEST t  
  join test t2 on t2.product = t.product

以下是所需结果:

Product Orderdate   Diffdays
A       1/1/2019        0
B       1/11/2019       10
C       1/15/2019       4
D       1/20/2019       5

实际结果:

Product orderdate   diffdays
A       1/1/2019          0
B       1/11/2019         0
C       1/15/2019         0
D       1/20/2019         0

4 个答案:

答案 0 :(得分:1)

每个产品只有一行,因此,如果您加入该行,则将自己与同一行连接起来,如您所见,datediff为零。

相反,您可以根据lag orderdate product,并将其用于datediff:

SELECT   product,
         orderdate,
         COALESCE(DATEDIFF(DAY, overdate, LAG(overdate) OVER (ORDER BY product)),0)
FROM     test
ORDER BY 1

答案 1 :(得分:0)

尝试延迟功能:

SELECT 
product,
ISNULL(
   DATEDIFF(DAY, lag(orderdate,1) OVER (ORDER BY orderdate), orderdate),0) AS DIF
FROM TEST
ORDER BY PRODUCT

答案 2 :(得分:0)

SELECT t.product, 
       t.orderdate, 
       IsNull(Datediff(day, Lag(t.orderdate, 1) 
                              OVER ( 
                                ORDER BY t.orderdate), t.orderdate), 0) 
FROM   test t 

答案 3 :(得分:0)

以下查询将满足您的问题。

SELECT X.Product,X.Orderdate,ISNULL(DATEDIFF(DAY,X.PREVDATE,X.Orderdate),0) AS DayDiff FROM (SELECT T.Product,T.Orderdate, LAG(T.Orderdate) OVER( ORDER BY ORDERDATE) AS PREVDATE  FROM Test T )X