cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
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
Community Manager
Community Manager
1 REPLY 1

Kaniz
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....

Welcome to Databricks Community: Lets learn, network and celebrate together

Join our fast-growing data practitioner and expert community of 80K+ members, ready to discover, help and collaborate together while making meaningful connections. 

Click here to register and join today! 

Engage in exciting technical discussions, join a group with your peers and meet our Featured Members.