实现说明
这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 incident_labels。
incident_labels 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。
机制上由这些部分组成:WHERE 只放行满足条件的行进入这条语句;用 MIN 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;DISTINCT 折叠重复行;必填列上的 NOT NULL 限定。
常见问题
这段 SQL 涉及哪些对象?
incident_labels。
核心语句
SELECT
incident_id,
STRING_AGG(label, ', ' ORDER BY first_seen) AS unique_by_first_seen
FROM (
SELECT incident_id, label, MIN(seen_order) AS first_seen
FROM incident_labels
WHERE label IS NOT NULL
GROUP BY incident_id, label
) AS deduped
GROUP BY incident_id
ORDER BY incident_id;
SELECT
incident_id,
STRING_AGG(DISTINCT label, ', ' ORDER BY label DESC) AS unique_desc
FROM incident_labels
GROUP BY incident_id
ORDER BY incident_id;
INSERT INTO incident_labels VALUES
(10, 1, 'db'),
(10, 2, 'timeout'),
(10, 3, 'db'),
(10, 4, NULL),
(20, 1, 'auth');
代码示例
CREATE TEMP TABLE incident_labels (
incident_id integer NOT NULL,
seen_order integer NOT NULL,
label text
);
INSERT INTO incident_labels VALUES
(10, 1, 'db'),
(10, 2, 'timeout'),
(10, 3, 'db'),
(10, 4, NULL),
(20, 1, 'auth');
-- DISTINCT + ORDER BY works when ORDER BY references the DISTINCT expression itself
SELECT
incident_id,
STRING_AGG(DISTINCT label, ', ' ORDER BY label DESC) AS unique_desc
FROM incident_labels
GROUP BY incident_id
ORDER BY incident_id;
-- To order unique labels by earliest seen_order, deduplicate first in a subquery
SELECT
incident_id,
STRING_AGG(label, ', ' ORDER BY first_seen) AS unique_by_first_seen
FROM (
SELECT incident_id, label, MIN(seen_order) AS first_seen
FROM incident_labels
WHERE label IS NOT NULL
GROUP BY incident_id, label
) AS deduped
GROUP BY incident_id
ORDER BY incident_id;