透视数据

Snowflake 中的数据类型与函数

Jake Roach

Field Data Engineer

汇总表

                   course_name  |  exam_type  |  avg_exam_score
                  ------------- | ----------- | ----------------
                    Calculus I  |  Exam 1     |       81.78
                    Calculus I  |  Exam 2     |       83.55
                    Calculus I  |  Final      |       80.93

                    Finance     |  Exam 1     |       89.47
                    Finance     |  Exam 2     |       90.39
                    Finance     |  Final      |       89.69

                    Marketing   |  Exam 1     |       94.11
                    Marketing   |  Exam 2     |       93.29
                    Marketing   |  Final      |       93.81
Snowflake 中的数据类型与函数

"透视"的表




         course_name  |    "Exam 1"   |    "Exam 2"   |  "Final"
        ------------- | ------------- | ------------- | ---------
          Calculus I  |     81.78     |     83.55     |   80.93
          Finance     |     89.47     |     90.39     |   89.69
          Marketing   |     94.11     |     93.29     |   93.81



Snowflake 中的数据类型与函数

创建透视表

SELECT
    *
FROM SCHEMA.TABLE

PIVOT(
-- 聚合函数 SUM(<1>)
-- 指定要从行转为列的字段 FOR <2> IN (ANY ORDER BY <2>) -- 不需要 GROUP BY! );

PIVOT 通过将值"透视"为列来输出聚合数据的另一种方式

  • SELECT * 可配合 EXCLUDE
  • PIVOT 写在 FROM ... 之后
  • <2> 中可用 ANY

$$

<1>:要聚合的字段

<2>:要转成列的行值

Snowflake 中的数据类型与函数

CTE 与透视数据

WITH exam_grades AS (
    SELECT
        ..., exam_score, exam_type
    FROM SCHEMA.TABLE
    WHERE ...
)

SELECT * -- 也可用 EXCLUDE FROM exam_grades PIVOT( AVG(exam_score) FOR exam_type IN (ANY ORDER BY exam_type) );

先定义一个 CTE,再用 PIVOT

$$

        `SELECT * FROM <cte>`

$$

$$

$$

exam_score:要聚合的字段

exam_type:要转成列的行值

Snowflake 中的数据类型与函数

按考试类型比较成绩

WITH exam_grades AS (
    SELECT 
        course_name, course_abbreviation, exam_score, exam_type
    FROM STUDENTS.grades
    WHERE course_level = '101'
)

SELECT * EXCLUDE course_abbreviation -- 从结果中移除 course_abbrevation FROM exam_grades
PIVOT( AVG(exam_score) FOR exam_type IN (ANY ORDER BY exam_type) );
Snowflake 中的数据类型与函数

按考试类型比较成绩

                 course_name  |   exam_type   |  avg_exam_score
                ------------- | ------------- | ----------------
                  Calculus I  |   Exam 1      |       81.78
                  Calculus I  |   Exam 2      |       83.55
                  Calculus I  |   Final       |       80.93

                  Finance     |   Midterm 1   |       89.47
                                     ...
                 course_name  |    "Exam 1 "  |    "Exam 2"   |  "Final"
                ------------- | ------------- | ------------- | ---------
                  Calculus I  |     81.78     |     83.55     |   80.93
                  Finance     |     89.47     |     90.39     |   89.69
                  Marketing   |     94.11     |     93.29     |   93.81
Snowflake 中的数据类型与函数

Vamos praticar!

Snowflake 中的数据类型与函数

Preparing Video For Download...