← 中文资源

简体中文版本

MODE WITHIN GROUP 求分组众数

mode() WITHIN GROUP 按出现频率返回分组内最高的非 NULL 值;同频并列返回任一值,FILTER 还能让只有达标的行参与投票。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 sales。 sales 是由本文件里的语句当场建出来的会话级临时表——只活在当前会话,会话结束就自动清掉。 用到的 SQL 构件:WHERE 决定这条语句会作用到哪些行;用 COUNT 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定。

常见问题

它引用了哪些表或 CTE?

引用的是 sales。

核心语句

SELECT
    region,
    mode() WITHIN GROUP (ORDER BY channel) AS top_channel,
    mode() WITHIN GROUP (ORDER BY channel)
        FILTER (WHERE amount >= 100) AS big_order_channel,
    count(*) AS samples
FROM sales
GROUP BY region
ORDER BY region;
INSERT INTO sales (region, channel, amount) VALUES
    ('emea', 'web', 120), ('emea', 'web', 80),  ('emea', 'api', 300),
    ('apac', 'api', 90),  ('apac', 'web', 140), ('apac', 'api', 60);
CREATE TEMP TABLE sales (
    region  text    NOT NULL,
    channel text    NOT NULL,
    amount  numeric NOT NULL
);

代码示例

-- mode() WITHIN GROUP returns the most frequent non-NULL value (the mode)
-- ties return one of the tied values, unspecified which: report copy must not claim a single winner
CREATE TEMP TABLE sales (
    region  text    NOT NULL,
    channel text    NOT NULL,
    amount  numeric NOT NULL
);

INSERT INTO sales (region, channel, amount) VALUES
    ('emea', 'web', 120), ('emea', 'web', 80),  ('emea', 'api', 300),
    ('apac', 'api', 90),  ('apac', 'web', 140), ('apac', 'api', 60);

SELECT
    region,
    mode() WITHIN GROUP (ORDER BY channel) AS top_channel,
    -- FILTER works for ordered-set aggregates too: only qualifying orders get a vote
    mode() WITHIN GROUP (ORDER BY channel)
        FILTER (WHERE amount >= 100) AS big_order_channel,
    -- sample size signals how much to trust the mode: two of three leading is not the same as a three-way tie
    count(*) AS samples
FROM sales
GROUP BY region
ORDER BY region;