79562520

Date: 2025-04-08 15:53:09
Score: 0.5
Natty:
Report link

I know this is an old question, but recently I need to do something like this and didn't find a simple answer googling for it. And bothers me that I need to create solutions if UNPIVOT can be used for it in a simple way. So, I create 2 UNPIVOT group of columns with a value for each. I think is more readable and clean.

SELECT 
    UNPVT_GROUP2.*
FROM (
    SELECT * FROM DB.SCHEMA.TABLE 
) TBL UNPIVOT (
    GROUP1_VALUE FOR GROUP1_NAME IN (COL_G1_01, COL_G1_02, COL_G1_03)
) UNPVT_GROUP1 UNPIVOT (
    GROUP2_VALUE FOR GROUP2_NAME IN (COL_G2_01, COL_G2_02, COL_G2_03)
) UNPVT_GROUP2 
WHERE
    UNPVT_GROUP2.FILTER_COL = 'FILTERVALUE';

Remembering that you can only read the fields from the last UNPIVOT, in this case UNPVT_GROUP2. If you try to do something like UNPVT_GROUP1.COL1, you'll get an error message like: "The column prefix 'UNPVT_GROUP1' does not match with a table name or alias name used in the query."

I hope this can help someone with the same problem as mine. Cheers!

Reasons:
  • Blacklisted phrase (1): Cheers
  • Blacklisted phrase (0.5): I need
  • Whitelisted phrase (-1): hope this can help
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Luiz Coelho