Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the result from string_agg()

People also ask

What does STRING_AGG do in SQL?

STRING_AGG is an aggregate function that takes all expressions from rows and concatenates them into a single string. Expression values are implicitly converted to string types and then concatenated. The implicit conversion to strings follows the existing rules for data type conversions.

When STRING_AGG is introduced in SQL Server?

The STRING_AGG function concatenates strings separated by a specified separator. This was introduced with SQL Server 2017.

How do you aggregate strings in SQL?

The STRING_AGG() is an aggregate function that concatenates rows of strings into a single string, separated by a specified separator. It does not add the separator at the end of the result string. In this syntax: input_string is any type that can be converted VARCHAR and NVARCHAR when concatenation.

Is STRING_AGG available in SQL Server 2016?

PSA: STRING_AGG is actually available for SQL Server 2016.


With postgres 9.0+ you can write:

select string_agg(product,' | ' order by product) from "tblproducts"

Details here.


https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT
  STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product)
FROM ... 

select string_agg(prod,' | ') FROM 
  (SELECT product as prod FROM tblproducts ORDER BY product )MAIN;

SQL FIDDLE