我有一个查询,该查询返回很多行。我需要最后一行和第一行中的值之间的差异。 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
答案 0 :(得分:1)
这可能不是最好的方法,但应该完成这项工作:
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
答案 1 :(得分:0)
您可以使用FIRST_VALUE和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
根据排序顺序返回每个组/结果集中的最后一个值。在此查询中,这与返回每一行的TotSoap_W1
值相同。为了使其返回所有结果中的最后一个值,我们需要添加ROWS BETWEEN UNBOUNDEDPRECEDING AND UNBOUNDED FOLLOWING
子句