I have this query (except for the last column) and what I want to do is the last columns followed by this logic:
if the code column is between 101 and 111 then we sum the values on VLR1 grouped by the PERIOD column and subtract by only one row of VLR2 (it can be the first since all the rows in one period are the same).
| PERIOD | CODE | VLR1 | VLR2 | DESIRED COLUMN |
|---|---|---|---|---|
| 2019-01 | 101 | 1000 | 100 | 5900 |
| 2019-01 | 101 | 2000 | 100 | 5900 |
| 2019-01 | 103 | 3000 | 100 | 5900 |
| 2019-01 | 722 | 0 | 0 | 0 |
I have more columns on my query than these displayed above and this is my current code:
(I know the second line of my code is not right as it is now but that is the "idea", I just don’t know how to fix it)
SELECT X.PERIOD, X.CODE, X.VLR1, X.VLR2,
(SELECT SUM(X.VLR1) - X.VLR2) GROUP BY PERIOD)
FROM
(
...
) X
ORDER BY X.PERIOD
>Solution :
Does the following query using a windowed sum work for you?
select *,
Sum(vlr1) over(
partition by period,
case when code >= 101 and code <= 111 then 1 end
) - vlr2 Desired_Column
from t
order by period, code, Vlr1;
See sample Fiddle