別名(Aliasing)— 球隊 BMI
一位籃球統計分析師想知道每支 NBA 球隊的平均身體質量指數(BMI),特別是平均 BMI 達到 25 或以上的球隊。為了在查詢中納入 Team,你需要把 Players 資料表與 PlayerStats 資料表做 JOIN。這個查詢需要使用別名,目的如下:
- 讓已連接的資料表與相關欄位容易辨識。
- 用來標示子查詢。
- 避免欄位名稱的歧義。
- 標示新建立的欄位。
本練習屬於課程
改進 SQL Server 中的查詢效能
練習說明
- 將新的平均 BMI 欄位命名為別名
AvgTeamBMI。 - 將
PlayerStats資料表命名為別名ps。 - 將「子查詢」命名為別名
p。 PlayerStats資料表與「子查詢」是以PlayerName欄位進行連接。請在連接條件中的PlayerName欄位加上相對應的別名。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
SELECT Team,
ROUND(AVG(BMI),2) AS ___ -- Alias the new column
FROM PlayerStats ___ ___ -- Alias PlayerStats table
INNER JOIN
(SELECT PlayerName, Country,
Weight_kg/SQUARE(Height_cm/100) BMI
FROM Players) ___ ___ -- Alias the sub-query
-- Alias the joining columns
ON ___.PlayerName = ___.PlayerName
GROUP BY Team
HAVING AVG(BMI) >= 25;