Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Yes, it is possible to implement SQL Server's STRING_AGG() function in queries that involve GROUP BY ROLLUP(). However, it requires some additional handling to concatenate the string values correctly for each group.

Here is an example query that uses the STRING_AGG() function with GROUP BY ROLLUP():

SELECT
  COALESCE(col1, 'Total') AS col1,
  COALESCE(col2, 'Total') AS col2,
  STRING_AGG(col3, ', ') AS col3_agg
FROM table1
GROUP BY ROLLUP(col1, col2)

In this query, the COALESCE() function is used to replace NULL values in the grouping columns with a default value of 'Total'. The STRING_AGG() function is then applied to the col3 column to concatenate the string values for each group. The GROUP BY ROLLUP() clause is used to produce subtotals and a grand total for the result set.

Note that the order of the columns in the GROUP BY ROLLUP() clause determines the order of the subtotals and the grand total.