I have the following result of a query:
P2_AU_CE | P2_03 |
P2_AU_CE | P2_04 |
P2_CN_MOCE_001 | P2_04 |
I would like to have the result shown this way instead:
P2_AU_CE | P2_03 | P2_04 |
P2_CN_MOCE | EMPTY | P2_04 |
I have the following result of a query:
P2_AU_CE | P2_03 |
P2_AU_CE | P2_04 |
P2_CN_MOCE_001 | P2_04 |
I would like to have the result shown this way instead:
P2_AU_CE | P2_03 | P2_04 |
P2_CN_MOCE | EMPTY | P2_04 |
3
Answers
Try this SQL query to get the results you want. In this query, in the first column the rows are grouped by the values, and for the conditional aggregation is used to spread the values from second column into the separate column. The empty cells are replaced with the text "EMPTY" by using the COALESCE function.
Hope it works 🙂
To achieve the desired result where you want to pivot the data and show it in a different format, you can use SQL to pivot the rows into columns. Since the values in the second column ("P2_03" and "P2_04") should become column headers, you can use conditional aggregation to achieve this. Here’s the SQL query to pivot your data:
Please replace your_table_name with the actual name of your table. This query uses the LEFT and CHARINDEX functions to extract the first part of column1 before the underscore, and then it uses conditional aggregation to pivot the data into the format you want. It will display "EMPTY" if there is no corresponding value in column2 for a particular combination of Col1.
The result will look like this:
This query will give you the desired output where the values in column2 become separate columns.
You can try using the
STRING_AGG()
function to join the non-null values in yourP2_03
andP2_04
columns to a single string, that is separated by a slash ‘|’.But if the value is ‘NULL`, you will then use the string ‘EMPTY’.