如何使用date diff在sql中获得这样的结果

时间:2014-11-26 19:51:42

标签: sql

ColA           ColB            RESULTCol
A      |    2/12/2014     |      0
A      |    2/13/2014     |      1      
A      |    2/14/2014     |      1
B      |    2/11/2014     |      0
B      |    2/16/2014     |      5
B      |    2/17/2014     |      1
C      |    2/19/2014     |      0
C      |    2/20/2014     |      1
C      |    2/22/2014     |      2
C      |    2/25/2014     |      3

如何使用日期差异功能从ColA和ColB获取ResultCol?

2 个答案:

答案 0 :(得分:1)

大多数数据库都支持ANSI标准lag()功能。这似乎正是您所寻找的:

select IDCode, DateValue,
       coalesce(datediff(day, lag(DateValue) over (partition by IDCode order by DateValue),
                         DateValue),
                0)
from taable t;

我不确定您使用的是哪个数据库;这使用SQL Server函数datediff()。 (其他数据库具有类似的功能。)

答案 1 :(得分:0)

以下是使用CTE

进行此操作的方法
;With Cte As
(
    Select  *, Row_Number() Over (Partition By ColA Order By ColB Asc) Row
    From    YourTable
)
Select      A.ColA, A.ColB, Coalesce(DateDiff(Day, B.ColB, A.ColB), 0) ResultCol
From        Cte A
Left Join   Cte B   On  A.ColA = B.ColA
                    And A.Row = B.Row + 1
Order By A.ColA Asc, A.ColB Asc