GROUP BY
在先前的練習中,你寫了一個獨立的 WHERE 查詢來計算特定地區損失的需求量。我們當然不希望為了「每一個」地區都各寫一次查詢。幸好,你不需要為「每一個」地區各自撰寫查詢。透過 GROUP BY,你可以一次就彙總你所選欄位中所有唯一值的總和。
你將回到 grid 資料表,計算所有地區的總需求損失。
本練習屬於課程
SQL Server 入門
練習說明
- 選取
nerc_region,以及各地區的demand_loss_mw總和。 - 排除
demand_loss_mw為 NULL 的列。 - 依
nerc_region分組結果。 - 依
demand_loss遞減排序。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Select the region column
SELECT
___,
-- Sum the demand_loss_mw column
SUM(___) AS demand_loss
FROM
grid
-- Exclude NULL values of demand_loss
WHERE
demand_loss_mw ___ ___ ___
-- Group the results by nerc_region
___ __
nerc_region
-- Order the results in descending order of demand_loss
ORDER BY
demand_loss ___;