Difference between SQL SERVER dates

3

I have a question in sql server .

Based on the table below, how can I take the difference in days which takes to go from one phase to another of the same client, ie phase to phase difference.

Example:

  • The difference between id 2 and 1 is 9 days;

  • Between id 3 and 2 are 10 days;

asked by anonymous 27.04.2018 / 22:48

3 answers

3

You can use the LEAD function that accesses the subsequent row data, or either, this function used in SELECT server to compare to current row with values from the next row

SELECT DATEDIFF(day, data , data_next)  AS sub
FROM (
  SELECT [data], lead([data],1,0) over (order by id) as data_next FROM test1) 
AS T

SQLFiddle Example

27.04.2018 / 23:20
0

Using the Datediff () you can get the difference between dates.

% w / w% below solves your problem for a specific case.

SQLFiddle - Online Example:

SELECT 
  DATEDIFF(
    day 
    , (SELECT Data FROM Teste WHERE ID =1) 
    , (SELECT Data FROM Teste WHERE ID =2)
  )  AS DiferencaEmDias

Ifyouwantedtoleavethedynamicsolution,youcancreateaSelectasintheexamplebelow,incaseitreceivesasaparametertwoprocedure.

Example:

CREATEPROCEDUREDiferencaFases@idInicialINT,@idFinalINTASSELECTDATEDIFF(day,(SELECTDataFROMTesteWHEREID=@idInicial),(SELECTDataFROMTesteWHEREID=@idFinal))ASDiferencaEmDiasGO

    
27.04.2018 / 23:04
0

To avoid using subselect in the select clause, you can cross-reference table data using one ranking per client.

So:

SELECT 
    SOURCE.ID,
    SOURCE.CLIENTE,
    SOURCE.FASE,
    SOURCE.DATA,
    DATEDIFF(DAY, QUERY.DATA, SOURCE.DATA) DIAS
FROM (SELECT RANK() OVER (PARTITION BY CLIENTE ORDER BY FASE) AS RANKING, 
             T.ID, 
             T.CLIENTE, 
             T.FASE, 
             T.DATA FROM Teste T) SOURCE
     LEFT JOIN (SELECT RANK() OVER (PARTITION BY CLIENTE ORDER BY CLIENTE, FASE) AS RANKING, 
                       T.CLIENTE,
                       T.FASE, 
                       T.DATA FROM Teste T) QUERY ON QUERY.CLIENTE = SOURCE.CLIENTE AND (QUERY.RANKING = SOURCE.RANKING - 1)

Depending on the real scenario where you intend to apply the performance gain while avoiding subselect, it can be very interesting.

This example is available in SQL Fiddle

    
27.04.2018 / 23:24