On Nov 28, 2015, at 1:35 PM, Sterpu Victor <victor@xxxxxxxx> wrote:
The > / < comparisons appear to be mutually exclusive in each LEFT JOIN clause, so it’s not apparent why aqjs3 is causing duplication, as you’ve stated. As far as I can see, without providing us with your table constraints/keys, there’s no way to determine what makes your ID values unique… However, if you defer your STRING_AGG until after you derive a distinct “staging” result set from the joins, then you can effect uniqueness - e.g. (air code): WITH q AS (SELECT aq.id aq_parent_id, atjs.id atjs_parent_id, CAST(aqjs1.id AS VARCHAR) child FROM ... GROUP BY aq.id, atjs.id, aqjs1.id) SELECT atjs_parent_id, STRING_AGG(child,’,’ ORDER BY aqjs.to_left) children FROM q LEFT JOIN (SELECT DISTINCT id_ad_query, to_left FROM administration.ad_query_join_select) aqjs ON … GROUP BY aq_parent_id, parent ORDER BY aq_parent_id, atjs.to_left; Something along these lines ‘may’ produce a unique set of child values for each id by which to perform a STRING_AGG on, but again, I can only guess based on the lack of definition provided for your table constraints. John |