iT邦幫忙

2024 iThome 鐵人賽

DAY 17
0

本系列對於基礎語法的最後一篇,想與大家分享使用PIVOT搭配聚合函數,可以將資料更靈活的做Excel的樞紐分析,以下透過簡單的例子教學。

基本語法

SELECT *
FROM (
    SELECT <columns>
    FROM <table>
)
PIVOT (
    <aggregation_function>(<pivot_column>)
    FOR <pivot_column> IN (<value1>, <value2>, ..., <valueN>)
);
  • <table>: 要轉換的原始表
  • <aggregation_function>: 聚合函數,如 SUM, AVG, COUNT
  • <pivot_column>: 需要被轉置的欄位
  • <value1>, <value2>, ..., <valueN>: 這些值會成為新的欄位名稱

樞紐Example

以下為學生的 數學英文 成績單,透過 PIVOT 來創造 By 科目 的成績表格

with scores as (
  select 'JACK' name, 45 score, 'Math' course from dual
  union all
  select 'AMY' name, 56 score, 'English' course  from dual
  union all
  select 'KAMY' name, 78 score, 'Math' course  from dual
  union all
  select 'Celine' name, 99 score, 'Math' course  from dual
  union all
  select 'Ryan' name, 100 score, 'English' course  from dual
)
select *
from scores
PIVOT(
    AVG(score)
    FOR course IN ('Math' as Math, 'English' as Eng)
)
;
  • 原始分數資料表
name score course
JACK 45 Math
AMY 56 English
AMY 78 Math
Celine 99 Math
Celine 99 English
JACK 100 English
  • 樞紐結果
name Math Eng
JACK 45 100
AMY 78 56
Celine 99 99

上一篇
Day 16 基礎-正規表示式
下一篇
Day 18 實戰-Hackerrank Easy篇
系列文
不居功的系統隱士 - 30天由淺入深學SQL25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言