'String aggregation in postgresql table using psycopg2

I have following table in Postgresql 11.0.

id   code   name1    name2
1    XXX    abc      sdf
1    XXX    def      null
2    ZZZ    zut      null
3    YYY    gtj      bzu
3    YYY    null     nuz

I would like to aggregate the values in name1 and name2 column for each id (in python). The below query runs perfectly in pgadmin but gives error through python script.

try:
    cursor.execute("""
            UPDATE tbl t1
            SET name1 = sub_q.name1,
                name2 = sub_q.name2
            FROM 
                (
                SELECT id, code, string_agg(name1, ' ; ') as name1, string_agg(name2, ' ; ') as name2
                FROM tbl as t2 
                GROUP BY t2.id, t2.code
                ) AS sub_q
            WHERE sub_q.id= t1.id
            ;
                        )
            """)
except:
    print ("The table cannot be created")

The expected output is:

id   code   name1       name2
1    XXX    abc; def     sdf
2    ZZZ    zut      null
3    YYY    gtj      bzu; nuz


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source