2
I have a user readout log structure by reference. As shown below.
SELECT L.LeituraID, L.UsuarioID, L.Referencia, L.Leitura
FROM Leituras AS L
|-----------|-----------|------------|---------|
| LeituraID | UsuarioID | Referencia | Leitura |
|-----------|-----------|------------|---------|
| 1         | 1         | 01/01/2018 | 52      |
| 2         | 2         | 01/01/2018 | 157     |
| 3         | 3         | 01/01/2018 | 73      |
| 4         | 1         | 01/02/2018 | 63      |
| 5         | 2         | 01/02/2018 | 171     |
| 6         | 3         | 01/02/2018 | 89      |
|-----------|-----------|------------|---------|
I need to take the user reading data by a reference date and make a consumption calculation.
To calculate the consumption you need to have the previous reading information.
I assembled the query by bringing the current reading data and a subquery to pick up the previous reading.
The problem is that this search with the subquery is taking too long.
Is there any way to get that previous reading in a faster way?
WITH cteLeituras AS (
    SELECT 
        L.LeituraID
        , L.UsuarioID
        , L.Referencia
        , L.Leitura
        (
            SELECT TOP 1 LA.Leitura 
            From Leituras AS LA 
            WHERE LA.UsuarioID = L.UsuarioID AND LA.Referencia < L.Referencia
            ORDER BY LA.Referencia DESC
        ) AS LeituraAnterior
    FROM Leituras AS L
    WHERE L.Referencia = '2018-02-01'
), cteLeiturasConsumo AS (
    SELECT 
        L.LeituraID
        , L.UsuarioID
        , L.Referencia
        , L.Leitura
        , L.LeituraAnterior
        , (L.Leitura - L.LeituraAnterior) AS Consumo
    FROM cteLeituras AS L 
)
|-----------|-----------|------------|---------|-----------------|---------|
| LeituraID | UsuarioID | Referencia | Leitura | LeituraAnterior | Consumo |
|-----------|-----------|------------|---------|-----------------|---------|
| 4         | 1         | 01/02/2018 | 63      | 52              | 11      |
| 5         | 2         | 01/02/2018 | 171     | 157             | 14      |
| 6         | 3         | 01/02/2018 | 89      | 73              | 16      |
|-----------|-----------|------------|---------|-----------------|---------|
What version of SQL Server?
– José Diz
@Josédiz is the 2016 version
– Danilo Ribeiro da Silveira