Chuyển đến nội dung chính
eLearner.app
Mô-đun 13 · Bài học 1 trong tổng số 449/57 trong khóa học~15 min
Bài học theo mô-đun (1/4)

Giới thiệu và mệnh đề OVER

Introduction and the OVER Clause

In the previous lessons we saw how to use GROUP BY to aggregate data. However, GROUP BY has a huge limitation: it collapses rows. If you group by city, you get a single row per city and lose the details of the individual customers.

This is where Window Functions come into play. They let you run aggregate calculations (such as sums or averages) while keeping the original rows.

The OVER() clause

The magic keyword is OVER(). It tells the database that the aggregate function (e.g. SUM, AVG, COUNT) should be treated as a window function, computed over the whole result set (the global "window") but applied and returned on every single row.

SQL
SELECT
  order_id,
  total_amount,
  AVG(total_amount) OVER() AS global_average
FROM orders;

In this example, we keep every individual order, but every row also has a global_average column with the average of all orders. Very useful, for instance, to measure how much an order deviates from the average!

tập thể dục#sql.m13.l1.e1
Nỗ lực: 0Đang tải…

Select the 'price' column from the 'products' table. Add a column called 'global_max_price' containing the maximum price computed with a window function over the entire table.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use MAX(price) combined with OVER().

Giải pháp khả dụng sau 3 lần thử

tập thể dục#sql.m13.l1.e2
Nỗ lực: 0Đang tải…

Extract 'id', 'price' and add the overall average price ('global_avg') from the 'products' table.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Just add AVG(price) OVER().

Giải pháp khả dụng sau 3 lần thử