I'm looking for a way to dynamically or automatically name the columns in my case statement below. Scenario - I'm trying to find out how many different companies of various industries are found in each country. The countries are the rows while the categories are the columns.
I'm using postgressql so pivot won't work and I don't have a new enough version where I can use cross-tab
I want to be able to replicate this for much larger scenarios where I won't have to worry about 'hardcoding' the cat_nbr and column names like I do here.
SELECT country,
count(CASE WHEN cat_nbr = 1 THEN company_code END) retail,
count(CASE WHEN cat_nbr = 2 THEN company_code END) finance,
count(CASE WHEN cat_nbr = 3 THEN company_code END) oil,
count(CASE WHEN cat_nbr = 4 THEN company_code END) tech
FROM global_companies
GROUP BY country
the table structure format in case it isn't clear has these columns:
country - cat_nbr - company_code - cat_desc.
Cat_desc is where I have hardcoded the words 'retail', 'finance', etc
Is there someway I can do this with less hardcoding in terms of what I refer to each cat_nbr/cat_desc? There are lots and lots of cat_nbrs and cat_descs.