14,697,269 members
See more:
I have this table :
```TBL_ENERGII
ID    | DateTime                | [CM1-Ea]
16431 | 2020-09-22 06:00:00.000 | 2627123.9
16432 | 2020-09-22 14:00:00.000 | 2627900.0
16433 | 2020-09-22 22:00:00.000 | 2628547.0
16434 | 2020-09-23 06:00:00.000 | 2629204.0
16435 | 2020-09-23 14:00:00.000 | 2629899.9
16436 | 2020-09-23 22:00:00.000 | 2630600.5```

I want to subtract the first value of the table from last value from the table. Yes this not the all data that this table has. The values are from @DataStart to @DataStop.

What I have tried:

I've tried :

```SELECT
(p2.[CM1-Ea]-p1.[CM1-Ea]) AS Diff
FROM
WHERE p1.DateTime IN (SELECT TOP 1 p.DateTime
WHERE p.DateTime BETWEEN @DataStart AND @DataStop )
AND p2.DateTime = (SELECT TOP 1 p.DateTime
ORDER BY p.DateTime DESC)```
Posted
Updated 28-Sep-20 3:47am

## Solution 1

Try:
```SELECT  b.[CM1-Ea] - a.[CM1-Ea] FROM
(SELECT TOP 1 [DateTime], [CM1-Ea] FROM TBL_ENERGII ORDER BY DateTime ASC) a,
(SELECT TOP 1 [DateTime], [CM1-Ea] FROM TBL_ENERGII ORDER BY DateTime DESC) b```
Maciej Los 28-Sep-20 6:10am

Paul, why to use subquery if there's a MIN and MAX function? Take a look at my answer.
OriginalGriff 28-Sep-20 6:26am

Because it's not the max or min CM1-Ea values he wants to subtract, it's the CM1-Ea values associated with the max and min DateTime values he's interested in.
Gaby94 28-Sep-20 6:33am

Yes @OriginalGriff is right, sorry if it was not that obvious

## Solution 4

If you're using SQL Server 2016 or later, you can use the FIRST_VALUE[^] and LAST_VALUE[^] functions. Depending on your indexes, this may be slightly more efficient.
```SELECT TOP 1
FIRST_VALUE([CM1-Ea]) OVER (ORDER BY [DateTime])
- LAST_VALUE([CM1-Ea]) OVER (ORDER BY [DateTime] RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
As Diff
FROM
WHERE
[DateTime] Between @DataStart And @DataStop
;```
NB: The `RANGE BETWEEN` clause is required on the `LAST_VALUE` call, otherwise the function will not take any rows after the first row into account.
Maciej Los 28-Sep-20 15:15pm

5ed!

## Solution 2

I figure it out on my own, istead of using p1.DateTime and p2.DateTime I used p.ID and p2.ID and it does provide the data I wanted.

```SELECT
(p2.[CM1-Ea]-p1.[CM1-Ea]) AS Diff
FROM
WHERE p1.ID IN (SELECT TOP 1 p.ID
WHERE p.DateTime BETWEEN @DataStart AND @DataStop )
AND p2.ID = (SELECT TOP 1 p.ID
WHERE p.DateTime BETWEEN @DataStart AND @DataStop
ORDER BY p.DateTime DESC)```
Maciej Los 28-Sep-20 6:11am

Please, see my comment to OriginalGriff's answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 OriginalGriff 150 Richard MacCutchan 90 BillWoodruff 75 Richard Deeming 55 KarstenK 40
 OriginalGriff 385 Richard Deeming 150 Rick York 120 BillWoodruff 115 Richard MacCutchan 90

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900