Answer the question
In order to leave comments, you need to log in
How to write a query to select relationships without PostgreSQL duplicates?
Good day!
Please help with a request. Actually, here is the database structure and query .
The essence of the problem is as follows: 1.
JOIN
' 2 tables (1 and 2), by several fields (no other way)
a logically correct result string (i.e. the grouping is needed exactly like this)
3. We are interested in the result in the last column ( array_agg ) The snag
is in the 5th line. If we remove DISTINCT , then an excess number of values is added to the results. If we leave DISTINCT - the same values "collapse", and the result is not correct.
Can you please tell me how to get unique values in the array_agg
column (in the form of an array), without multiple duplicates and without "collapsing" the same values? Those. the result should be something like: "b1, b1, b2, b2, b3, b3" or "b1, b2, b3, b1, b2, b3" (or in any other order).
Answer the question
In order to leave comments, you need to log in
SELECT
t2.b1,
t2.b2,
t2.b3,
ARRAY_AGG(t2.value)
FROM table2 t2
WHERE EXISTS (
SELECT 1
FROM table1 t1
WHERE t1.a1 = t2.b1
AND t1.a2 = t2.b2
AND t1.a3 = t2.b3
)
GROUP BY t2.b1, t2.b2, t2.b3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question