To avoid using subselect in clause select
, you can cross table data using one ranking per customer.
Thus:
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 actual scenario where you intend to apply performance gain while avoiding subselect can be quite interesting.
This example is available in SQL Fiddle
Has the answer worked out for you Lucas? if yes you can accept as an answer to your question!?
– novic