Okay, this is a common point of confusion because "group by that as well" when "that" is an aggregated set can be interpreted in a few ways. Let's break it down.
First, let's set up some example tables and data:
-- Table 1: Parent (1-side of the relationship)
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(100) NOT NULL,
category VARCHAR(50)
);
-- Table 2: Child (N-side of the relationship)
CREATE TABLE product_tags (
tag_id SERIAL PRIMARY KEY,
product_id INT REFERENCES products(product_id),
tag_name VARCHAR(50) NOT NULL
);
-- Sample Data
INSERT INTO products (product_name, category) VALUES
('Laptop Pro', 'Electronics'),
('Mechanical Keyboard', 'Electronics'),
('Desk Chair Ergo', 'Furniture'),
('LED Monitor', 'Electronics'),
('Coffee Table', 'Furniture'),
('Gaming Headset', 'Electronics');
INSERT INTO product_tags (product_id, tag_name) VALUES
(1, 'High-End'), (1, 'Portable'), (1, 'Sleek'),
(2, 'Gaming'), (2, 'Clicky'), (2, 'RGB'),
(3, 'Ergonomic'), (3, 'Adjustable'),
(4, 'High-Res'), (4, 'Gaming'), (4, 'Curved'),
(5, 'Wood'), (5, 'Modern'),
(6, 'Wireless'), (6, 'Gaming'), (6, 'Noise Cancelling'), (6, 'RGB');
Interpretation 1: "For each group based on table1.column, give me the distinct set of table2.column values."
This is the most straightforward interpretation. You want to group by a column from products (e.g., category) and for each category, get a list of all distinct tag_names associated with products in that category.
Solution: Use ARRAY_AGG(DISTINCT ...)
SELECT
p.category,
ARRAY_AGG(DISTINCT pt.tag_name ORDER BY pt.tag_name) AS distinct_tags_for_category
FROM
products p
JOIN
product_tags pt ON p.product_id = pt.product_id
GROUP BY
p.category
ORDER BY
p.category;
Explanation:
p.category: The column from table1 (products) you are grouping by.
ARRAY_AGG(DISTINCT pt.tag_name ORDER BY pt.tag_name):
ARRAY_AGG(): Aggregates values into an array.
DISTINCT: Ensures that only unique tag_names are included in the array for each group.
ORDER BY pt.tag_name: Crucially important! This ensures that the array elements are always in the same order, regardless of the underlying data storage or join order. Without ORDER BY, {'a', 'b'} and {'b', 'a'} would be considered different arrays, even though they represent the same set of values. Sorting makes them consistent.
Result:
category | distinct_tags_for_category
--------------+----------------------------
Electronics | {Clicky,Curved,Gaming,High-End,High-Res,Noise Cancelling,Portable,RGB,Sleek,Wireless}
Furniture | {Adjustable,Ergonomic,Modern,Wood}
This query groups by p.category and for each such group, it produces one row with the category and the aggregated set of tags.
Interpretation 2: "I want to group by a column of table1 AND find table1 entries that have the exact same aggregated set of table2 values."
This is where the "group by that as well" becomes tricky. You're saying, "Show me product categories where the product_name is the same, AND the entire set of associated tags is the same." This implies finding patterns of (product_name, set_of_tags).
If you were trying to group by product_name and then also group by the array of tags, you'd typically do this in a two-step process using a Common Table Expression (CTE).
Scenario: Let's say you want to identify which product_names have the same set of tags, even if they are different products (e.g., if you had 'Laptop A' with {'Gaming', 'RGB'} and 'Laptop B' with {'Gaming', 'RGB'}). For our data, product_name is unique, so let's adjust the example slightly to make this clearer. Suppose we are grouping by category and want to see if multiple categories have the exact same set of tags. (In our data, they don't, but let's illustrate the concept.)
Solution: Use a CTE to first get the aggregated sets, then group by the set.
WITH ProductTagSets AS (
SELECT
p.product_id,
p.product_name,
p.category,
ARRAY_AGG(DISTINCT pt.tag_name ORDER BY pt.tag_name) AS distinct_product_tags
FROM
products p
JOIN
product_tags pt ON p.product_id = pt.product_id
GROUP BY
p.product_id, p.product_name, p.category -- Group by product to get tags for each product
)
SELECT
pts.distinct_product_tags, -- This is the set you are grouping by
ARRAY_AGG(pts.product_name ORDER BY pts.product_name) AS products_with_this_tag_set,
COUNT(*) AS number_of_products_with_this_tag_set
FROM
ProductTagSets pts
GROUP BY
pts.distinct_product_tags -- Group by the array of tags
HAVING
COUNT(*) > 1 -- Optional: only show tag sets shared by multiple products
ORDER BY
number_of_products_with_this_tag_set DESC, pts.distinct_product_tags;
Explanation:
-
ProductTagSets CTE:
- This CTE first calculates the unique set of
tag_names for each individual product.
- We group by
product_id, product_name, and category to ensure each row represents one product and its unique tags.
- The
ARRAY_AGG(DISTINCT ... ORDER BY ...) is crucial here to generate a canonical representation of the tag set for each product.
-
Outer Query:
- We now select from
ProductTagSets.
GROUP BY pts.distinct_product_tags: This is the key. Since distinct_product_tags is an ARRAY, Postgres can group by it. If two products have an identical array of tags (because we sorted them consistently), they will fall into the same group.
ARRAY_AGG(pts.product_name): For each unique tag set, this collects all the product_names that share that exact set of tags.
COUNT(*): Counts how many products share that specific tag set.
HAVING COUNT(*) > 1: This is optional. It filters the results to only show tag sets that are associated with more than one product. If you remove it, you'll see all unique tag sets, even those only used by one product.
Result (for our current data):
Since each product in our sample data has a unique combination of tags, the HAVING COUNT(*) > 1 clause will filter out all results. If you remove HAVING COUNT(*) > 1, you would see:
distinct_product_tags | products_with_this_tag_set | number_of_products_with_this_tag_set
------------------------------------------+----------------------------------------------+--------------------------------------
{Adjustable,Ergonomic} | {Desk Chair Ergo} | 1
{Clicky,Gaming,RGB} | {Mechanical Keyboard} | 1
{Gaming,High-Res,Curved} | {LED Monitor} | 1
{High-End,Portable,Sleek} | {Laptop Pro} | 1
{Wireless,Gaming,Noise Cancelling,RGB} | {Gaming Headset} | 1
{Wood,Modern} | {Coffee Table} | 1
If you had products with identical tag sets (e.g., Laptop Pro also had {'High-End', 'Portable', 'Sleek'}), the result would look more like:
distinct_product_tags | products_with_this_tag_set | number_of_products_with_this_tag_set
------------------------------------------+----------------------------------------------+--------------------------------------
{High-End,Portable,Sleek} | {Laptop Pro, Some Other Laptop} | 2
Clarifying your use case:
The first interpretation is by far the most common for the phrasing "aggregate into a set and group by a column of table 1". The second interpretation is for a more advanced "find groups of items that share the exact same aggregated characteristics."
If neither of these exactly matches what you mean, please provide a small example of your expected output given some input data, and I can refine the query!