Aggregation Functions
CoddyのSQLジャーニー「基礎」セクションの一部 — レッスン 68/72。
集計関数は、AVG() や MAX()、またはその他の集計関数を現在の行まで計算するために使用されます。
例えば、各終了期間までの最大収益を計算することができます:
| 月 | 収益 | 地域 |
| 4 | 40 | 東 |
| 5 | 20 | 東 |
| 6 | 60 | 西 |
| 7 | 55 | 西 |
| 8 | 61 | 東 |
SELECT month, revenue, MAX(revenue) OVER (ORDER BY month ASC) as max_revenue
from table1これは次を返します:
| 月 | 収益 | 最大収益 |
| 4 | 40 | 40 |
| 5 | 20 | 40 |
| 6 | 60 | 60 |
| 7 | 55 | 60 |
| 8 | 61 | 61 |
4ヶ月目と5ヶ月目の最大収益は40、6ヶ月目と7ヶ月目は60、そして8ヶ月目は61です。これは、より大きな新しい収益が見つかると、古い値を破棄して、それまでの最大値を使用するためです。
AVG() 関数については、以下のようになります:
SELECT month, revenue, AVG(revenue) OVER (ORDER BY month ASC) as avg_revenue
from table1| 月 | 収益 | 平均収益 |
| 4 | 40 | 40 |
| 5 | 20 | 30 |
| 6 | 60 | 40 |
| 7 | 55 | 43.75 |
| 8 | 61 | 47.2 |
PARTITION BYを使用して、特定のカテゴリごとに計算をグループ化することもできます。例えば:
SELECT month, revenue, region,
MAX(revenue) OVER (PARTITION BY region ORDER BY month ASC) as max_revenue
FROM table1次のような結果になります:
| 月 | 収益 | 地域 | max_revenue |
| 4 | 40 | 東 | 40 |
| 5 | 20 | 東 | 40 |
| 6 | 60 | 西 | 60 |
| 7 | 55 | 西 | 60 |
| 8 | 61 | 東 | 61 |
これで、最大値は各リージョンごとに個別に計算されます。EastリージョンとWestリージョンは、それぞれの累積最大値を独立して維持します。
チャレンジ
簡単利用可能なテーブルとカラム:
<strong>books</strong>:<strong>book</strong>,<strong>page</strong>,<strong>words</strong>
各書籍について、書籍名、ページ番号、各ページの単語数を表示し、以下を計算してください:
- その書籍のいずれかのページで見つかった最大単語数
- 書籍全体の1ページあたりの平均単語数
- 現在のページの単語数と、その書籍の1ページあたりの平均単語数との差
結果を book と page 番号の順に並べて表示してください。
以下のカラムを返してください:
bookpagewordsmax_words_in_bookavg_words_per_pagediff_from_avg
チートシート
集計を伴うウィンドウ関数は、現在の行に関連する一連の行にわたって値を計算します。累積計算を行うには、OVER句とORDER BYを組み合わせて使用します。
SELECT column,
MAX(column) OVER (ORDER BY column ASC) as running_max,
AVG(column) OVER (ORDER BY column ASC) as running_avg
FROM tableカテゴリごとに計算をグループ化するには、PARTITION BYを使用します。
SELECT column, category,
MAX(column) OVER (PARTITION BY category ORDER BY column ASC) as max_per_category
FROM tableこれにより、カテゴリごとに個別に最大値が計算され、独立した累積計算が維持されます。
自分で試してみよう
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
基礎のすべてのレッスン
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns9Multiple tables
Basic Join Part 1Basic Join Part 2Recap - JoinSelf joinRecap - Self JoinUnionSimplify queries, WITH keywordRecap - With QueriesRecap - Real Estate Contractor12Window Functions part 2
RANK & DENSE_RANK FunctionsRecap - RANK & DENSE_RANKNTILE FunctionAggregation FunctionsROWS & RANGE Criterion