I've come up with a query to create concatenated string based on a conditional statement using STRING_AGG in Postgress. That works just fine but I want to sort the result as well without duplicating the CASE.
This is what I have now:
SELECT
STRING_AGG(distinct name, ', ' ORDER BY name),
STRING_AGG(
DISTINCT
CASE WHEN something = true THEN 'type1'
WHEN something_else = true THEN 'type2'
ELSE 'type3'
END, ', '
ORDER BY
CASE WHEN something = true THEN 'type1'
WHEN something_else = true THEN 'type2'
ELSE 'type3'
END
)
from organisations
..but I want to do something like this to not have the duplicated code and remove rows and complexity from my query but I can't figure out how to make it work, this is fake code that doesn't work obviously, but you get the idea:
SELECT
STRING_AGG(distinct name, ', ' ORDER BY name) names,
STRING_AGG(
DISTINCT (
CASE WHEN something = true THEN 'type1'
WHEN something_else = true THEN 'type2'
ELSE 'type3'
END
) as types, ', ' ORDER BY types) types
from organisations