实现说明
实际执行的是 SELECT——涉及的对象是 team_members。
机制上由这些部分组成:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;WHERE 只放行满足条件的行进入这条语句;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序。
常见问题
这里涉及哪些关系(表/CTE)?
引用的是 team_members。
代码示例
WITH team_members(team, name) AS (
VALUES
('core', 'ada'),
('core', 'miles'),
('core', 'zoe'),
('infra', 'raj'),
('infra', 'mei')
)
SELECT
team,
-- ORDER BY 写在聚合内部:拼接顺序稳定,不依赖行的物理顺序
string_agg(name, ', ' ORDER BY name) AS roster_sorted,
-- FILTER 收窄参与聚合的行,再按倒序拼接
string_agg(name, ' & ' ORDER BY name DESC)
FILTER (WHERE name <> 'zoe') AS roster_desc_no_zoe,
array_agg(name ORDER BY name) AS roster_array
FROM team_members
GROUP BY team
ORDER BY team;