如何在SQL Server中获得差异?

时间:2017-08-06 01:02:53

标签: sql-server date

我遇到了一个我不知道如何解决的问题。

我想在2个值之间获得3天的差异。但是,当我查询过滤一个值时,我得到了结果:

SELECT
    BeginRange, EndRange,
    DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays,
    Code
FROM  
    (SELECT 
         MAX(DataTransacao) OVER (ORDER BY DataTransacao) BeginRange,
         LEAD(DataTransacao) OVER (ORDER BY DataTransacao) EndRange,
         Code
     FROM 
         #Relatorio1    
     WHERE
         Code = '000008480700001') AS C
WHERE  
    c.EndRange > c.BeginRange
    -- AND datediff(day,BeginRange, EndRange) >= 3 
ORDER BY 
    DifferenceDays, Code 

结果:

BeginRange  EndRange    DifferenceDays  Code
-------------------------------------------------------
20170601    20170602    1               000008480700001
20170602    20170605    3               000008480700001 

但是当我在没有过滤器的情况下运行查询时,我没有得到上面的结果。

SELECT
    BeginRange, EndRange,
    DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays,
    Code
FROM  
    (SELECT 
         MAX(DataTransacao) OVER (ORDER BY DataTransacao) BeginRange,
         LEAD(DataTransacao) OVER (ORDER BY DataTransacao) EndRange,
         Code
     FROM 
         #Relatorio1) AS C
WHERE  
    c.EndRange > c.BeginRange
    -- AND datediff(day,BeginRange, EndRange) >= 3 
ORDER BY 
    DifferenceDays, Code;  

结果

没什么

我做错了什么?我无法得到第一个查询中的第一个结果。

1 个答案:

答案 0 :(得分:0)

您的问题有点难以理解,但我认为您只需要partition by

SELECT BeginRange, EndRange,
       DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays
       Code
FROM (SELECT MAX(DataTransacao) OVER (PARTITION BY Code ORDER BY DataTransacao) as BeginRange,
             LEAD(DataTransacao) OVER (PARTITION BY Code ORDER BY DataTransacao) as EndRange,
             Code
      FROM #Relatorio1

     ) C
WHERE  c.EndRange > c.BeginRange
 -- AND datediff(day,BeginRange, EndRange) >= 3 
ORDER BY DifferenceDays, Code;