SQL 服务器:从第一行减去最后一行

SQL Server : subtract last row from first row

我有一个查询 returns 很多行。我需要最后一行和第一行中的值之间的差异。 TimeCol 是一个 DateTime 列,所有其他列都是 float.

类型

我当前的(简化的)查询是这样的:

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

这可能不是最好的方法,但应该可以做到:

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

您可以使用 FIRST_VALUE and LAST_VALUE 分析函数:

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 return根据排序顺序设置每个 group/result 中的最后一个值。在此查询中,它与 returning 每行的 TotSoap_W1 值相同。要使其 return 成为所有结果中的最后一个值,我们需要添加 ROWS BETWEEN UNBOUNDEDPRECEDING AND UNBOUNDED FOLLOWING 子句