【发布时间】:2018-04-15 14:07:09
【问题描述】:
我提出了一个查询,用于在 Postgress 中使用 STRING_AGG 的条件语句创建连接字符串。这工作得很好,但我也想对结果进行排序而不重复 CASE。
这就是我现在拥有的:
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
..但是我想做这样的事情来避免重复的代码并从我的查询中删除行和复杂性,但我不知道如何使它工作,这是明显不起作用的假代码,但你明白了:
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
【问题讨论】:
标签: sql postgresql string-aggregation