Lessons › SQL › Deep Dive: Advanced Window Functions
SQL lesson
STRING_AGG()
STRING_AGG() collapses many rows of text into a single joined value, stitching them together with a separator you choose.
Try this lesson free →Example
Combining Retail Details with STRING_AGG()
SELECT customer_id,
STRING_AGG(category, ', ' ORDER BY category) AS purchased_categories
FROM orders
GROUP BY customer_id| customer_id | purchased_categories |
|---|---|
| C101 | Beauty, Clothing, Electronics |
| C102 | Electronics, Fashion |
Step by step
- AS gives a column a friendlier name in the result.
SELECT customer_id, STRING_AGG(category, ', ' ORDER BY category) AS purchased_categories - FROM tells SQL which table to pull the data from.
SELECT customer_id, STRING_AGG(category, ', ' ORDER BY category) AS purchased_categories FROM orders - GROUP BY collapses rows that share the same value into one row per group.
SELECT customer_id, STRING_AGG(category, ', ' ORDER BY category) AS purchased_categories FROM orders GROUP BY customer_id;
Practice
1. Using orders, write a query that concatenates all category values per order_id into a comma-separated list.
SELECT order_id, STRING_AGG(category, ', ') FROM orders GROUP BY order_id2. Using store_sales, write a query that concatenates all store_id values per sale_id into a comma-separated list.
SELECT sale_id, STRING_AGG(store_id, ', ') FROM store_sales GROUP BY sale_id3. Using products, write a query that concatenates all brand values per brand into a comma-separated list.
SELECT brand, STRING_AGG(brand, ', ') FROM products GROUP BY brand4. Using reviews, write a query that concatenates all review_id values per product_id into a comma-separated list.
SELECT product_id, STRING_AGG(review_id, ', ') FROM reviews GROUP BY product_id5. Using employees, write a query that concatenates all employee_id values per department into a comma-separated list.
SELECT department, STRING_AGG(employee_id, ', ') FROM employees GROUP BY departmentLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →