I am new to snowflake and I have a scenario with table having below data,
Combined1 Combined2 Common_code
Name John ABC123
City NY ABC123
Sex M ABC123
Country USA ABC123
Name John ABC123
City BF ABC123
Sex M ABC123
Country USA ABC123
Name Lucy XYZ456
City CB XYZ456
Sex F XYZ456
Country UK XYZ456
So that I want to transpose the table so that the result would look like
Name City Sex Country Common_code
John NY M USA ABC123
John BF M USA ABC123
Lucy CB F UK XYZ456
I have tried multiple approaches using PIVOT, FLATTEN but couldn't crack this up. Main condition is I don't want to lose any record as per the above example. Any response or solution is highly appreciated in Snowflake.
so using a CTE for the data:
so here is the most likely "optimal" aggregation version that you want to avoid, albeit it, you have duplicate values in your common_code, so this data appears suspect.
But the above relies on the "common code" being distinct per thing of interest. Which it is not, thus the two rows.
Which means we can just do it the classic worst way possible, and let the DB build all combinations, and then throw most the work away, way:
which gives:
this could be framed in sub-selects (or CTE's) and make NATURAL JOIN do some work also like so:
but now the column order is less under our control (only because I allowed the join order to define it).