2017-08-06 37 views
1

我正面臨一個我不知道如何解決的問題。如何在SQL Server中獲得不同的日子?

我想得到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; 

結果

NOTHING

我在做什麼錯?我無法得到第一個查詢中得到的第一個結果。

回答

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; 
+0

感謝所有! 這正是我尋找的。 我真的很感謝你的幫助! 再次感謝所有! – Luiz