Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot perform an aggregate function on an expression containing an aggregate or a subquery with STRING_AGG

I am trying to query information from 2 tables. The PrimaryTable I simply want to return all columns from all rows in that table. The SupportTable I want to just get all of the ID’s from that table that are associated with a row in the PrimaryTable and return that as a comma separated string. Note: the SupportTable might have zero or many rows that are associated with a row in the PrimaryTable.

Here’s the query I tried that is throwing the error.

SELECT
    PrimaryTable.*,
    STRING_AGG(
        (
            SELECT
                SupportTable.Id
            FROM
                SupportTable
            WHERE
                SupportTable.AssociatedPrimaryTableId = PrimaryTable.Id
        ),
    ',') AS AssociatedSupportTableIds
FROM
    PrimaryTable;

I’ve found other SO posts that address the error message I’m seeing, but none of those solutions use STRING_AGG() and they all seem to do GROUP BY in their primary table which I don’t want to do.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

they all seem to do GROUP BY in their primary table which I don’t want to do.

Too bad. You will need GROUP BY for this, but maybe not the way you expect. Try building the column like this:

SELECT
    PrimaryTable.*,
    (
        SELECT
            STRING_AGG(SupportTable.Id, ',')
        FROM
            SupportTable
        WHERE
            SupportTable.AssociatedPrimaryTableId = PrimaryTable.Id
        GROUP BY AssociatedPrimaryTableId 
    )
    AS AssociatedSupportTableIds
FROM
    PrimaryTable;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading