简体   繁体   中英

SQL Server : subtract last row from first row

I have a query that returns a lot of rows. I would need the difference between the values in the last row and the first row. TimeCol is a DateTime column, all other columns are of type float .

My current (simplified) query is this:

select 
    timeCol, TotSoap_W1, TotSoap_W2, TotEnergy
from
    TotEnergy
where 
    TimeCol >= '2019-03-01 00:00:00' and timeCol < '2019-03-02 00:00:00'
order by 
    TimeCol asc

This might not be the best way of doing but should do the job:

SELECT B.TotSoap_W1-A.TotSoap_W1 as TotSoap_W1, B.TotSoap_W2-A.TotSoap_W2 as TotSoap_W2, B.TotEnergy-A.TotEnergy as TotEnergy
FROM
(select TOP(1) timeCol, TotSoap_W1, TotSoap_W2, TotEnergy
from TotEnergy
where TimeCol >= '2019-03-01 00:00:00' and timeCol < '2019-03-02 00:00:00'
order by TimeCol ASC) A,
(select TOP(1) timeCol, TotSoap_W1, TotSoap_W2, TotEnergy
from TotEnergy
where TimeCol >= '2019-03-01 00:00:00' and timeCol < '2019-03-02 00:00:00'
order by TimeCol DESC
) B

You can use the FIRST_VALUE and LAST_VALUE analytic functions :

select top 1 LAST_VALUE(TotSoap_W1) OVER (ORDER BY TimeCol ROWS
                                          BETWEEN UNBOUNDEDPRECEDING AND UNBOUNDED FOLLOWING)
             - FIRST_VALUE(TotSoap_W1)
from TotEnergy
where TimeCol >= '2019-03-01 00:00:00' and timeCol < '2019-03-02 00:00:00'
order by TimeCol asc

LAST_VALUE returnes the last value in each group/result set according to the sorting order. In this query, it would be the same as returning each row's TotSoap_W1 value. To make it return the last value in all the results, we need to add the ROWS BETWEEN UNBOUNDEDPRECEDING AND UNBOUNDED FOLLOWING clause

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM