1
1
# Unpivot multiple columns in Snowflake
2
2
3
+ ## Example 1: Unpivot 3 Columns
3
4
Suppose you have a Wide Table format Performance Ratings data as following:
4
5
5
6
| 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
26
27
| Harpo Marx | COMEDY_RATING | 4 | Nice | COMEDY_COMMENTS | |
27
28
| Harpo Marx | MUSICAL_PERFORMANCE_RATING | 4 | Best performance Award! | MUSICAL_PERFORMANCE_COMMENTS | |
28
29
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
32
31
33
32
``` sql
34
33
select
@@ -45,21 +44,32 @@ where split(skill, '_')[0] = split(skill_comments, '_')[0];
45
44
46
45
```
47
46
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
| [email protected] | [email protected] |
53
+ | Steph Andersson
| Anders Bloom
| Stephen McDonalds
| [email protected] | [email protected] |
48
54
49
- ## Using UNION ALL
55
+ You can use the following SQL to transpose this into a long table format as following:
50
56
51
57
``` 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 ]
52
64
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
- ;
65
65
```
66
+
67
+
68
+ | CHILD_NAME | GUARDIAN_NAME | GUARDIAN_EMAIL |
69
+ | -----------------| -------------------| -----------------|
70
+ | Lynn Evans
| Amrika Hernandez
| [email protected] |
71
+ | Lynn Evans
| Steve Evans
| [email protected] |
72
+ | Steph Andersson
| Anders Bloom
| [email protected] |
73
+ | Steph Andersson
| Stephen McDonalds
| [email protected] |
74
+
75
+
0 commit comments