Skip to content
Advertisement

Returning multiple aggregated columns from Subquery

I am trying to extend an existing query by aggregating some rows from another table. It works when I only return one column like this:

Then I tried to add another column for the aggregated volume:

However, this returns the following error:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

I experimented a bit with the EXISTS keyword, but couldn’t figure out how to make it work. Also I’m not sure whether this is the way to go in my case.

The desired output would be like so:

Advertisement

Answer

Instead of using DISTINCT and subqueries, use GROUP BY and normal joins to get the aggregates. And always use aliases, it will make your life easier:

Another option is to APPLY the grouped up subquery:

You can also use CROSS APPLY and leave out the GROUP BY (), this uses a scalar aggregate and returns 0 instead of null for no rows.

One last point: DISTINCT in a joined query is a bit of a code smell, it usually indicates the query writer wasn’t thinking too hard about what the joined tables returned, and just wanted to get rid of duplicate rows.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement