Issue
This Content is from Stack Overflow. Question asked by jj89
I have a Table ‘Meter1’ in my MSSQL database DB_TEST. Table structure is like this,
MeterID | Timestamp | Value |
---|---|---|
7 | 2022-09-16 11:00:00.000 | 1800 |
7 | 2022-09-16 12:00:00.000 | 1805 |
7 | 2022-09-16 13:00:00.000 | 1820 |
7 | 2022-09-16 14:00:00.000 | 1860 |
7 | 2022-09-16 15:00:00.000 | 1875 |
I need to calculate the hourly consumption by substracting the current value – previous value.
I have achieved this by using LAG function,
SELECT [MeterID]
,[Timestamp]
,[Value]
,VALUE - LAG (VALUE)
OVER (ORDER BY TIMESTAMP) AS Consumption
FROM [DB_TEST].[dbo].[Meter1]
& the results like this
MeterID | Timestamp | Value | Consumption |
---|---|---|---|
7 | 2022-09-16 11:00:00.000 | 1800 | NULL |
7 | 2022-09-16 12:00:00.000 | 1805 | 5 |
7 | 2022-09-16 13:00:00.000 | 1820 | 15 |
7 | 2022-09-16 14:00:00.000 | 1860 | 40 |
7 | 2022-09-16 15:00:00.000 | 1875 | 15 |
But how can I update or Insert the same results to my existing table with another column “Consumption”.
Solution
This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.
This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.