Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL code for sum by grouping by another column

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading