Skip to content
Advertisement

Oracle SQL: how to call created columns (alias) for pivot tables in a subquery

This is my first question in this community. It has helped me a lot before, so thank you all for being out there!

I have a problem with ORACLE PLSQL, I’m trying to create a pivot table that counts the number of people that are in a given salary range. I want cities as rows and salary_range as columns. My problem is when I select a column alias for the pivot table.

In table A I have the rows of all employees and their salaries, and in table B, I have their city. Both of them are linked by a key column named id_dpto. First, I join both tables selecting employee names, salaries, and cities. Second, I use CASE WHEN to create the range of salaries (less than 1000 and between 1000 and 2500 dollars) and give it the column alias SALARY_RANGE. Until here, everything is ok and the code runs perfectly.

My problem is on the third step. I use a subquery and PIVOT command to create the pivot to count by cities and salary_range, but when I use the select command in the alias it doesn’t work, my error message is "'F'.'SALARY_RANGE' INVALID IDENTIFYER". Can you help me what is the proper way to select a created column (salary_range) in a pivot table? I’ve tried both, with the F after the from and without it.

Initial data base

Desired result:

city salary less than 1000 salary between 1000 and 2500
NY 2 1
London 0 2

My code:

Thanks for helping me!

Advertisement

Answer

I think you should use * and exclude SALARY and NAMES from subquery:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement