Closed. This question needs details or clarity . It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post .
Closed 7 days ago.
Improve this question
I need to compute a running difference between InterimData values across different years.
Year | Month | Provider | ProviderName | InterimData |
---|---|---|---|---|
2022 | 8 | 1 | A | 3866.666667 |
2022 | 9 | 1 | A | 3866.666667 |
2022 | 12 | 1 | A | 3866.666667 |
2023 | 3 | 1 | A | 7416.666667 |
2023 | 3 | 2 | B | 7416.666667 |
Constant = 12800
Expected Output:
| Year | FinalValue | Logic |
| ------------ | ------------ | ------------ |
| 2022 | 8933.333333 | (Constant-Distinct InterimData of 2022 Year) |
| 2023 | 1516.666666 | (FinalValue of 2022 - Distinct interimData of 2023 Year) |
I've tried using the LAG
function, but it's not working out as expected. I am using sql server 2022.
Can you please help me?
3条答案
按热度按时间fcwjkofz1#
LAG
can't help you here because it doesn't carry information from all previous records.You could solve this problem by:
Output:
Check the demo here .
nzk0hqpo2#
dbfiddle demo
t
, also add row numbers,oknrviil3#
you can use cte and window function I used recursive Query and everything is dynamic first you find min Year and calculate first formula to Min Year and Last formula to other Year
You can insert Base data with the following statements: