数値計算

Snowflake のデータ型と関数

Jake Roach

Field Data Engineer

数値計算

3種類の数値計算と操作のイラスト。

Snowflake のデータ型と関数

数値の比較

比較演算子は複数の値を比較・評価するために使用する

  • =、2つの値が等しいか?
  • !=、2つの値が等しくないか?
  • <、一方の値が他方より小さいか?
  • >、一方の値が他方より大きいか?
  • <=、以下
  • >=、以上

$$

            true または false を返す!

$$

        1 = 1,   -- true

1 != 1, -- false
1 < 2, -- true
1 > 2, -- false
1 <= 2, -- true
2 >= 2 -- true
... WHERE 1 = 1 -- Filter records
Snowflake のデータ型と関数

Snowflake での算術演算

SELECT

    <#> + <#>,        -- 2 + 2  ->  4
    <field> - <#>,    -- 4 - 1  ->  3
    <field> * <#>,    -- 3 * 2  ->  6
    <field> / <#>,    -- 9 / 3  ->  3

                ...
  • # と field の組み合わせで演算可能

算術演算子は数値の「計算」を行うために使用する

$$

  • +、加算
  • -、減算
  • *、乗算
  • /、除算
Snowflake のデータ型と関数

算術演算

SELECT
    student_name, exam_score,

exam_score + 10 AS add_points, -- Add 10 points to each student's grade
exam_score * curve AS curved, -- Curve the grade by 10%
exam_score / 2 AS weighted -- Reduce the weight of the test
FROM STUDENTS.grades;
              student_name  |   exam_score   |  add_points  |  curved  |  weighted  
             -------------- | -------------- | ------------ | -------- | ----------
               Ryan         |       78       |      88      |   85.8   |     39
               Tatiana      |       89       |      99      |   97.9   |    44.5
               Pankaj       |       74       |      84      |   81.4   |     37
Snowflake のデータ型と関数

集計関数はサマリーデータを生成する

GROUP BY 集計レコードのイラスト。

Snowflake のデータ型と関数

集計関数

 SELECT

<1>,
SUM(<field>), -- Returns the total of a column
AVG(<field>) -- Finds the average value of a column
FROM ...
GROUP BY <1>;

非集計フィールドは必ず GROUP BY すること!

  • GROUP BY ALL
Snowflake のデータ型と関数

集計関数

SELECT
    exam_name,

    SUM(correct_answers) AS total_correct_answers,      -- Total # correct
    AVG(exam_score) AS avg_exam_score,                  -- Average exam score


ROUND(AVG(exam_score), 1) AS rounded_exam_score -- ROUND(<value>, <n>)
FROM STUDENTS.grades GROUP BY exam_name; -- GROUP BY to aggregate records, otherwise error

ROUND() は丸める値と小数点以下の桁数を引数に取る

Snowflake のデータ型と関数

集計関数

   exam_name    |  total_correct_answers  |  avg_exam_score  |  rounded_avg_exam_score 
  ------------- | ----------------------- | ---------------- | ------------------------ 
   Calculus I   |           871           |      89.11111    |           89.1     
   Biology      |           776           |      87.47777    |           87.5
   English III  |           541           |      91.33333    |           91.3
   Python       |          1179           |      92.78787    |           92.8
   Finance      |           349           |      96.14156    |           96.1

以下を使用して生成された値:

  • SUM(correct_answers)
  • AVG(exam_score)
  • ROUND(AVG(exam_score), 2)
Snowflake のデータ型と関数

練習しましょう!

Snowflake のデータ型と関数

Preparing Video For Download...