1.LISTAGG
WITHIN GROUP
Indicates that the aggregation will follow the specified ordering within the grouping set.
If WITHIN GROUP is not specified and no other LISTAGG, ARRAY_AGG, or XMLAGG is included in the same
SELECT clause with ordering specified, the ordering of strings within the result is not deterministic.
If WITHIN GROUP is not specified, and the same SELECT clause has multiple occurrences of XMLAGG, ARRAY_AGG, or LISTAGG that specify ordering, the same ordering is used for the result of the LISTAGG function invocation.
ORDER BY
Specifies the order of the rows from the same grouping set that are processed in the aggregation. If the ORDER BY clause cannot distinguish the order of the column data, the rows in the same grouping set are arbitrarily ordered.
sort-key
The sort key can be a column name or a sort-key-expression. If the sort key is a constant, it does not refer to the position of the output column (as in the ORDER BY clause of a query), but it is simply a constant, which implies no sort key.
The result data type of LISTAGG is based on the data type of string-expression:
If the data type of string-expression is CHAR(n) or VARCHAR(n), the data type of result is VARCHAR( MAX(4000, n))
If the data type of string-expression is GRAPHIC(n or VARGRAPHIC(n), the data type of result is VARGRAPHIC( MAX(2000, n))
The result data type can exceed VARCHAR(4000) or VARGRAPHIC(2000) if a derived size is used to determine the size of the result, to a maximum for the result data type. The following example successfully yields a return data type of VARCHAR(10000):
LISTAGG(CAST(NAME AS VARCHAR(10000)), ',')