Ask Your Question
1

Is it possible to implement SQL Server's STRING_AGG() function in queries that involve GROUP BY ROLLUP()?

asked 2023-05-29 07:03:31 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-29 07:22:01 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-29 07:03:31 +0000

Seen: 7 times

Last updated: May 29 '23