11# Unpivot multiple columns in Snowflake
22
3+ ## Example 1: Unpivot 3 Columns
34Suppose you have a Wide Table format Performance Ratings data as following:
45
56| NAME | ACTING_RATING | ACTING_COMMENTS | COMEDY_RATING | COMEDY_COMMENTS | MUSICAL_PERFORMANCE_RATING | MUSICAL_PERFORMANCE_COMMENTS |
@@ -26,9 +27,7 @@ and you need to convert it to a Long Table Format as following
2627| Harpo Marx | COMEDY_RATING | 4 | Nice | COMEDY_COMMENTS | |
2728| Harpo Marx | MUSICAL_PERFORMANCE_RATING | 4 | Best performance Award! | MUSICAL_PERFORMANCE_COMMENTS | |
2829
29- This can be achieve by using the UNPIVOT function or the UNION ALL in Snowflake
30-
31- ## Using UNPIVOT
30+ This can be achieve by using the UNPIVOT function as following
3231
3332``` sql
3433select
@@ -45,21 +44,32 @@ where split(skill, '_')[0] = split(skill_comments, '_')[0];
4544
4645```
4746
47+ ## Example 2: Unpivot 2 Columns
48+ Suppose you have a Wide Table format Children Guardian contact information as following:
49+
50+ | CHILD_NAME | GUARDIAN1_NAME | GUARDIAN2_NAME | GUARDIAN1_EMAIL | GUARDIAN2_EMAIL |
51+ | -----------------| ------------------| -------------------| -----------------| -----------------|
52+ | Lynn Evans | Amrika Hernandez | Steve Evans | amrika@fun.com | steve@fun.com |
53+ | Steph Andersson | Anders Bloom | Stephen McDonalds | anders@fun.com | Stephen@fun.com |
4854
49- ## Using UNION ALL
55+ You can use the following SQL to transpose this into a long table format as following:
5056
5157``` sql
58+ select child_name, guardian_name, guardian_email
59+ from student_guardian_info
60+ unpivot include nulls (guardian_name for name in (guardian1_name, guardian2_name))
61+ unpivot include nulls (guardian_email for email in (guardian1_email, guardian2_email))
62+ -- Following where clause is added to filter the unmatched rows
63+ where split(name, ' _' )[0 ] = split(email, ' _' )[0 ]
5264
53- select NAME
54- , ' ACTING_RATING' as SKILL, ACTING_RATING as SKILL_RATING, ACTING_COMMENTS as SKILL_COMMENTS
55- from performer_ratings
56- union all
57- select NAME
58- , ' COMEDY_RATING' , COMEDY_RATING, COMEDY_COMMENTS
59- from performer_ratings
60- union all
61- select NAME
62- , ' MUSICAL_PERFORMANCE_RATING' , MUSICAL_PERFORMANCE_RATING, MUSICAL_PERFORMANCE_COMMENTS
63- from performer_ratings
64- ;
6565```
66+
67+
68+ | CHILD_NAME | GUARDIAN_NAME | GUARDIAN_EMAIL |
69+ | -----------------| -------------------| -----------------|
70+ | Lynn Evans | Amrika Hernandez | amrika@fun.com |
71+ | Lynn Evans | Steve Evans | steve@fun.com |
72+ | Steph Andersson | Anders Bloom | anders@fun.com |
73+ | Steph Andersson | Stephen McDonalds | Stephen@fun.com |
74+
75+
0 commit comments