cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

Dynamically specify pivot column in SQL

erigaud
Honored Contributor

Hello everyone !

I am looking for a way to dynamically specify pivot columns in a SQL query, so it can be used in a view. However we don't want to hard code the values that need to become columns, and would rather extract it from another table.

I've seen other posts on internet asking the same question but without any luck 😕

Here's what we have currently :

SELECT * FROM table PIVOT (sum(my_value)
FOR mapping in ('col1', 'col2', ...)

 Instead we want to use a table table_mapping containing all the values that should go in the list, is there any way to do that in sql ? 

Thank you !

1 ACCEPTED SOLUTION

Accepted Solutions

Kaniz_Fatma
Community Manager
Community Manager
1 REPLY 1

Kaniz_Fatma
Community Manager
Community Manager

Hi @erigaud, In Databricks SQL, you can’t use a dynamic list of columns directly in the PIVOT clause. 

 

However, there is a workaround using DataFrames in PySpark

 

This approach allows you to pivot on the mapping column dynamically. The distinct values in the mapping column will become the columns in the pivoted DataFrame.

 

If you strictly want to use SQL, you might need to generate your SQL query string with the pivot col....

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group