I have a table similar to the following: (only an example to narrow the problem)
I need to get to this result in which in the current column for the C concept I have the result of the negative B concept from the previous column. Suppose I only have data until Feb , in that case I generate an auxiliary column that I name Mar where I see that logic impacted and Jan will have the results of 2016 .
How could I achieve the result I'm looking for?
This is the SQL that I tried, but it does not give me the expected results:
SELECT year_id, id, concept,
CASE WHEN concept <> 'C' THEN SUM(CASE WHEN month_id = 201701 then value else 0 end)
ELSE SUM(CASE WHEN month_id = 201612 and concept = 'B' then value else 0 end)end as Jan,
CASE WHEN concept <> 'C' THEN SUM(CASE WHEN month_id = 201702 then value else 0 end)
ELSE SUM(CASE WHEN month_id = 201701 and concept = 'B' then value else 0 end)end as Feb,
CASE WHEN concept = 'C' THEN SUM(CASE WHEN month_id = 201701 and concept = 'B' then value else 0 end) else 0 end as Mar
from aux
group by year_id, id, concept
order by year_id, id, concept;
Demo: link .