1

There is a table:

[region] [country] [month] [VAL] [VAL_PY]
EU Poland January x a
EU Poland January x1 a2
EU Poland February xx aa
EU France January y b
NA Brazil February z c
... ... ... ... ...

there is a need to make another table based on the one above, such as the one below, one row for one country, 12 new columns = 12 months, the value in each country/month is the KPI:

[region] [country] [January] February] ... [December]
EU Poland KPI KPI ... KPI
EU France KPI KPI ... KPI
... ... KPI KPI ... KPI

The KPI code:

CASE WHEN  sum(A."value_py")=0 THEN 0 
else round(((sum("value")-sum("value_py"))/sum("value"))*100,1 
END

Please help me, I can find the solution where there are duplicates in every country which is not acceptable

3
  • How many months do you need to push out columnwise? Commented Apr 13, 2021 at 13:12
  • all, 12 months. Commented Apr 13, 2021 at 13:13
  • the KPI should be calculated for every month separately Commented Apr 13, 2021 at 13:13

1 Answer 1

1

You are pivoting the data. You can use FILTER to retrieve data for each specific column.

For example:

select
  region,
  country,
  case when sum(a.val_py) filter(where month = 'January') = 0 then 0 
       else round(((sum(val) filter(where month = 'January') - 
            sum(val_py) filter(where month = 'January')) / 
            sum(val_py) filter(where month = 'January')) * 100, 1) 
  end as january,
  case when sum(a.val_py) filter(where month = 'February') = 0 then 0 
       else round(((sum(val) filter(where month = 'February') - 
            sum(val_py) filter(where month = 'February')) / 
            sum(val_py) filter(where month = 'February')) * 100, 1) 
  end as february,
  -- add the rest of the months here...
from t
group by region, country
Sign up to request clarification or add additional context in comments.

1 Comment

@Piotr It was a typo. It should say GROUP BY. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.