在SQL(PSQL)中,如何对行的分区进行分组(如何嵌套分组)?

In SQL (PSQL), how to group by partitions of rows (how to do nested group by)?

问题的措辞有待改进,不知道如何准确描述。

给定一个 table foo,计算每个人会说多少种语言,按格式分组。示例:

 name |  format  |  language
------+----------+------------
 abe  | compiled | golang
 abe  | compiled | c
 abe  | scripted | javascript
 jon  | scripted | ruby
 jon  | scripted | javascript
 wut  | spoken   | english
(6 rows)

结果:

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

可以使用以下方法创建示例数据:

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' )
;

我试过使用 windowing 函数 count(*) over (partition by format) 但它不会压缩行,它需要一个嵌套的 window 按名称,然后按格式,而count(*) ... group by name 单独使用会将结果压缩为每个名称一行。

使用group by子句:

select name, format, count(*)
from foo
group by name, format;

但是,如果您想使用 window 函数,那么您也可以这样做:

select distinct name, format, 
       count(*) over (partition by name, format)
from foo f;