I understand you want to group by both a column from table 1 and an aggregated set of distinct values from table 2. Let me clarify to make sure I understand correctly:
You have:
- Table 1 (parent) with a 1-to-many relationship to Table 2 (child)
- You're currently doing
GROUP BY table1.column
- You want to also group by the distinct set of values from a column in table 2
Could you confirm if you want something like this scenario:
If you have orders (table 1) and order_items (table 2), and order_items has a "category" column, do you want to group orders that have the exact same set of distinct categories?
For example:
- Order 1 has items in categories {A, B}
- Order 2 has items in categories {A, B}
- Order 3 has items in categories {A, C}
Orders 1 and 2 would be in the same group (both have category set {A, B}), while Order 3 would be in a different group?
If this is what you're looking for, you can achieve it using array aggregation:
SELECT
t1.column1,
ARRAY_AGG(DISTINCT t2.column2 ORDER BY t2.column2) as distinct_set,
COUNT(*) as group_count
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.table1_id
GROUP BY t1.column1, ARRAY_AGG(DISTINCT t2.column2 ORDER BY t2.column2)
However, you can't directly use aggregate functions in GROUP BY. Instead, you'd need to use a subquery or CTE:
WITH aggregated AS (
SELECT
t1.id,
t1.column1,
ARRAY_AGG(DISTINCT t2.column2 ORDER BY t2.column2) as distinct_set
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.table1_id
GROUP BY t1.id, t1.column1
)
SELECT
column1,
distinct_set,
COUNT(*) as group_count
FROM aggregated
GROUP BY column1, distinct_set;
Is this the kind of grouping you're trying to achieve?