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

Nhóm với PHẦN THAM GIA THEO

Grouping with PARTITION BY

Having global calculations on every row is handy, but often it is not enough. We may want to compute the average per category or per customer, while keeping the original detail on every row.

This is where PARTITION BY inside the OVER(...) clause comes in.

How PARTITION BY works

Conceptually it behaves similarly to GROUP BY, but instead of collapsing rows in the result, it only defines the boundary of the "window" of data on which the function will operate to compute the result for the single row.

SQL
SELECT
  product_name,
  category_id,
  price,
  AVG(price) OVER(PARTITION BY category_id) AS cat_avg_price
FROM products;

Each product row keeps its own details, and the cat_avg_price column will show the average limited to the products in its same category.

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

From the 'products' table, extract 'id', 'category_id' and 'price'. Add a 'category_total' column computing the SUM of 'price' for each 'category_id' using window functions.

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

Use SUM(price) OVER(PARTITION BY category_id).

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

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

From the 'reviews' table, show 'product_id', 'rating' and 'avg_product_rating' (the average rating partitioned by product). Show all rows.

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

Use AVG(rating) and PARTITION BY product_id. Cast it to NUMERIC if needed.

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