You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何实现多维度分组统计?以人员语言格式统计为例

解决方案:按姓名和格式分组统计语言数量

这其实是个典型的多维度分组聚合需求,你需要同时按name和format两个字段来分组,之前尝试的窗口函数或单一字段分组都没命中核心需求,具体实现如下:

正确的SQL查询语句

SELECT 
  name,
  format,
  COUNT(*) AS count
FROM foo
GROUP BY name, format
ORDER BY name, format;

为什么之前的方法不生效?

  • 使用count(*) over (partition by format):窗口函数的作用是为每一行添加对应分组的统计值,不会合并行,所以结果行数和原表一致,只是每行多了该format的总数量,无法实现你需要的合并统计效果。
  • 仅用GROUP BY name:这样只会按姓名维度合并数据,无法区分同一个人下不同format的语言数量,比如Abe的编译型和脚本型语言会被统计到同一行,不符合按format细分的需求。

示例数据与验证

创建示例表与插入数据

create table foo (
  name varchar(40) not null,
  format varchar(40) not null,
  language varchar(40) not null
);

insert into foo values
  ( 'abe', 'compiled', 'golang' ),
  ( 'abe', 'compiled', 'c' ),
  ( 'abe', 'scripted', 'javascript' ),
  ( 'jon', 'scripted', 'ruby' ),
  ( 'jon', 'scripted', 'javascript' ),
  ( 'wut', 'spoken', 'english' );

执行查询后的期望结果

name | format   | count
------+----------+-------
 abe  | compiled |     2
 abe  | scripted |     1
 jon  | scripted |     2
 wut  | spoken   |     1

内容的提问来源于stack exchange,提问作者Billiam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:11:25